//the text to link code (uriaggressive) is from Kim A. Brandt. See http://userscripts.org/scripts/show/7122
const SS_uriaggressive = /[a-z][a-z0-9+-.]*:((\/\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:]|%[a-f0-9]{2})*@)?((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([a-z0-9-\._~!$&'\(\)\/\*\+,;=]|%[a-f0-9]{2})+(:[0-9]+)?(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)|(\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)?)|(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*))+(\?([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?(#([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?/i;
const SS_uri = /((http)s?|(ftp)|(mailto)):((\/\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:]|%[a-f0-9]{2})*@)?((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([a-z0-9-\._~!$&'\(\)\/\*\+,;=]|%[a-f0-9]{2})+(:[0-9]+)?(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)|(\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)?)|(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*))+(\?([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?(#([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?/i;

const SS_uri2_57 = /[a-z0-9+-.(@)?]*\b\.((name)|([A-za-z]){2,3})\b([A-Za-z0-9$_+-=!*();&%/?:~.]*)?/i;
const SS_uri2_56 = /[a-z0-9+-.(@)?]*\b\.(com|net|org|edu|uk|au)\b([A-Za-z0-9$_+-=!*();&%/?:~.]*)?/i;

const SS_uri2 = /[^\.\(\)\"\s:-][a-z0-9+-.\(@\)?]*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=&%/?:~])*([\.,*;!\(\)](?=[-A-Za-z0-9$_+=*\(\);&%/?:~]))*)*/i;
const SS_uri2RnD2 = /[^\.\(\)\"\s:]{1,}(([a-z0-9+-.\(@\)?]+\.)*(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=&%/?:~])*([\.,*;!\(\)](?=[-A-Za-z0-9$_+=*\(\);&%/?:~]))*)*)/i;
// const SS_uri2_66 = /[^\.\(\)\"\s:][a-z0-9+-\(@\)?]*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=&%/?:~])*([\.,*;!\(\)](?=[-A-Za-z0-9$_+=*\(\);&%/?:~]))*)*/i;
const SS_uri2_63_1 = /(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!@](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*/i;
const SS_uri2RnD = /(([-A-Za-z0-9$_+=&%~])*([\.@](?=[A-Za-z0-9]))?)*\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*/i;

const SS_illegal = /^(a|button|label|legend|option|script|select|style|textarea|title)$/i;

var SS_prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var SS_alertTimeOut = 1000;

const SS_ulreplacement = "<u>$1</u>";

//pref consts
const SMACK_AUTOURL   = "extensions.swaksmack.autourl_boolpref1";
const SMACK_EASYURL   = "extensions.swaksmack.easyurl_boolpref1";
const SMACK_MAXURL = "extensions.swaksmack.maxurl_boolpref1";
const SMACK_MAXLENGTH = "extensions.swaksmack.maxurllength_intpref";
const SMACK_TRUNCURL = "extensions.swaksmack.truncurl_stringpref";
const SMACK_OUTWITALERT = "extensions.swaksmack.outwitwarn_pref1";
const SMACK_OUTWITVOTEALERT = "extensions.swaksmack.outwitvotewarn_pref1";
const SMACK_OUTWITRANDOM = "extensions.swaksmack.outwitrandom_pref1";
const SMACK_GURUGUESSALERT = "extensions.swaksmack.guruguesswarn_pref1";
const SMACK_SMACKPOTALERT = "extensions.swaksmack.smackpotwarn_pref1";
const SMACK_POLLINTERVAL = "extensions.swaksmack.pollinterval_intpref";
const SMACK_ALTALERTMONITOR = "extensions.swaksmack.altalertmonitor_boolpref1";
const SMACK_ENABKEALERTMONITORDELAY = "extensions.swaksmack.enablealertmonitor_boolpref1";

const SMACK_GLOBAL_ENABLEHL = "extensions.swaksmack.hl.enablehl_boolpref1";

const SMACK_THEME_ENABLE = "extensions.swaksmack.theme.enabletheme_boolpref1";
const SMACK_THEME_CHATTC = "extensions.swaksmack.theme.textcolor1_stringpref";
const SMACK_THEME_CHATBTC = "extensions.swaksmack.theme.bkcolor1_stringpref";
const SMACK_THEME_CHATNICK = "extensions.swaksmack.theme.chatNick_stringpref";
const SMACK_THEME_CHATGURU = "extensions.swaksmack.theme.chatGuru_stringpref";
const SMACK_THEME_CHATTIME = "extensions.swaksmack.theme.chatTime_stringpref";
const SMACK_THEME_CHATACTIONS = "extensions.swaksmack.theme.chatActions_stringpref";
const SMACK_THEME_CHATLINKS = "extensions.swaksmack.theme.chatLinks_stringpref";
const SMACK_THEME_BKGRD = "extensions.swaksmack.theme.cBkgrd_stringpref";
const SMACK_THEME_USERTHEMES = "extensions.swaksmack.theme.userThemes_stringpref";
const SMACK_THEME_CURRENTTHEME = "extensions.swaksmack.theme.currentTheme_stringpref";

//these are grouped with the ignore options for the sake of how the current comment processing is performed
const SMACK_ENABLECAPSUPRESSION = "extensions.swaksmack.ignore.enableCapsSupression_boolpref1";
const SMACK_CAPSTHESHOLD = "extensions.swaksmack.ignore.enableCapsThreshold_intpref1";

const SMACK_IGNORECASEHL = "extensions.swaksmack.hl.ignorecasehl_boolpref1";
const SMACK_IGNORESPHL = "extensions.swaksmack.hl.ignoreselfposts_boolpref1";
const SMACK_ENABLELRHL = "extensions.swaksmack.hl.enableinlrhl_boolpref1";
//const SMACK_KEYWORDHL1 = "extensions.swaksmack.keywordshl1_stringpref";
//const SMACK_TCHL1 = "extensions.swaksmack.hltextcolor1_stringpref";
//const SMACK_BTCHL1 = "extensions.swaksmack.hlbkcolor1_stringpref";
//const SMACK_UNDERLINEHL1 = "extensions.swaksmack.hlunderline1_boolpref1";
const SMACK_ITALICHL1 = "extensions.swaksmack.hlitalic1_boolpref1";
const SMACK_BOLDHL1 = "extensions.swaksmack.hlbold1_boolpref1";
//const SMACK_CHATWILDCARD = "extensions.swaksmack.chatwildcard_boolpref1";
const SMACK_BLOCKWILDCARD = "extensions.swaksmack.blockwildcard_boolpref1";
//const SMACK_OUTLINEHL1 = "extensions.swaksmack.postoutlinehl_boolpref1";
//const SMACK_USERNAMEONLYHL1 = "extensions.swaksmack.usernameonlyhl_boolpref1";
//const SMACK_WORDONLYHL1 = "extensions.swaksmack.wordonlyhl_boolpref1";
//const SMACK_USERNAMEHL1 = "extensions.swaksmack.usernamehl1_stringpref";
const SMACK_HL_ENABLEJFEMPLOYEE = "extensions.swaksmack.hl.enableJFEmployee_boolpref1";
const SMACK_HL_JFEMPLOYEEOPT = "extensions.swaksmack.hl.jellyfishemployee_stringpref";
const SMACK_HL_DYNKWOPT = "extensions.swaksmack.hl.dynamickeyword_stringpref";
const SMACK_HL_DYNUNOPT = "extensions.swaksmack.hl.dynamicusername_stringpref";

const SMACK_ENABLEHL1 = "extensions.swaksmack.hl.enablehl1_boolpref1";
const SMACK_KEYWORDHL1 = "extensions.swaksmack.hl.keywordshl1_stringpref";
const SMACK_USERNAMEHL1 = "extensions.swaksmack.hl.usernamehl1_stringpref";
const SMACK_TCHL1 = "extensions.swaksmack.hl.hltextcolor1_stringpref";
const SMACK_BTCHL1 = "extensions.swaksmack.hl.hlbkcolor1_stringpref";
const SMACK_OUTLINEHL1 = "extensions.swaksmack.hl.postoutlinehl1_boolpref1"
const SMACK_USERNAMEONLYHL1 = "extensions.swaksmack.hl.usernameonlyhl1_boolpref1";
const SMACK_CHATWILDCARD1 = "extensions.swaksmack.hl.chatwildcard1_boolpref1";
const SMACK_UNDERLINEHL1 = "extensions.swaksmack.hl.hlunderline1_boolpref1";
const SMACK_WORDONLYHL1 = "extensions.swaksmack.hl.wordonlyhl1_boolpref1";
const SMACK_CHATINFOHL1 = "extensions.swaksmack.hl.chatinfohl1_boolpref1";
const SMACK_KEYWORDIGNOREHL1 = "extensions.swaksmack.hl.keywordignore1_stringpref";
const SMACK_USERNAMEIGNOREHL1 = "extensions.swaksmack.hl.usernameignore1_stringpref";

const SMACK_ENABLEHL2 = "extensions.swaksmack.hl.enablehl2_boolpref1";
const SMACK_KEYWORDHL2 = "extensions.swaksmack.hl.keywordshl2_stringpref";
const SMACK_USERNAMEHL2 = "extensions.swaksmack.hl.usernamehl2_stringpref";
const SMACK_TCHL2 = "extensions.swaksmack.hl.hltextcolor2_stringpref";
const SMACK_BTCHL2 = "extensions.swaksmack.hl.hlbkcolor2_stringpref";
const SMACK_OUTLINEHL2 = "extensions.swaksmack.hl.postoutlinehl2_boolpref1"
const SMACK_USERNAMEONLYHL2 = "extensions.swaksmack.hl.usernameonlyhl2_boolpref1";
const SMACK_CHATWILDCARD2 = "extensions.swaksmack.hl.chatwildcard2_boolpref1";
const SMACK_UNDERLINEHL2 = "extensions.swaksmack.hl.hlunderline2_boolpref1";
const SMACK_WORDONLYHL2 = "extensions.swaksmack.hl.wordonlyhl2_boolpref1";
const SMACK_CHATINFOHL2 = "extensions.swaksmack.hl.chatinfohl2_boolpref1";
const SMACK_KEYWORDIGNOREHL2 = "extensions.swaksmack.hl.keywordignore2_stringpref";
const SMACK_USERNAMEIGNOREHL2 = "extensions.swaksmack.hl.usernameignore2_stringpref";

const SMACK_ENABLEHL3 = "extensions.swaksmack.hl.enablehl3_boolpref1";
const SMACK_KEYWORDHL3 = "extensions.swaksmack.hl.keywordshl3_stringpref";
const SMACK_USERNAMEHL3 = "extensions.swaksmack.hl.usernamehl3_stringpref";
const SMACK_TCHL3 = "extensions.swaksmack.hl.hltextcolor3_stringpref";
const SMACK_BTCHL3 = "extensions.swaksmack.hl.hlbkcolor3_stringpref";
const SMACK_OUTLINEHL3 = "extensions.swaksmack.hl.postoutlinehl3_boolpref1"
const SMACK_USERNAMEONLYHL3 = "extensions.swaksmack.hl.usernameonlyhl3_boolpref1";
const SMACK_CHATWILDCARD3 = "extensions.swaksmack.hl.chatwildcard3_boolpref1";
const SMACK_UNDERLINEHL3 = "extensions.swaksmack.hl.hlunderline3_boolpref1";
const SMACK_WORDONLYHL3 = "extensions.swaksmack.hl.wordonlyhl3_boolpref1";
const SMACK_CHATINFOHL3 = "extensions.swaksmack.hl.chatinfohl3_boolpref1";
const SMACK_KEYWORDIGNOREHL3 = "extensions.swaksmack.hl.keywordignore3_stringpref";
const SMACK_USERNAMEIGNOREHL3 = "extensions.swaksmack.hl.usernameignore3_stringpref";

const SMACK_ENABLEIGNORE1 = "extensions.swaksmack.ignore.enableignoreposts_boolpref1";
const SMACK_FUNIGNORE1 = "extensions.swaksmack.ignore.funignore_boolpref1";
const SMACK_IGNORELIST1 = "extensions.swaksmack.ignore.ignorelist1_stringpref";
const SMACK_IGNORELIST2 = "extensions.swaksmack.ignore.ignorelist2_stringpref";
const SMACK_ENABLE_FUNLIST = "extensions.swaksmack.ignore.enableuserfunlist_boolpref1";
const SMACK_FUNLIST_FILE = "extensions.swaksmack.ignore.userfunlistfile_stringpref";
const SMACK_ENABLE_NOOBIGNORE = "extensions.swaksmack.ignore.enableNoobIgnore_boolpref1";
const SMACK_NOOBIGNORE_THRESHOLD = "extensions.swaksmack.ignore.noobIgnoreThreshold_intpref1";


const SMACK_IGNORELISTATTEND = "extensions.swaksmack.ignore.ignorelistattend1_stringpref";
const SMACK_ENABLE_FUNAVATAR = "extensions.swaksmack.ignore.enableuserfunavatar_boolpref1";
const SMACK_CHATSPEED = "extensions.swaksmack.adv.chatspeed_intpref";
const SMACK_DEBUGENABLED = "extensions.swaksmack.adv.debugenabled_boolpref";
const SMACK_DEBUGINFO = "extensions.swaksmack.adv.debuginfo_stringpref";
const SMACK_AUDIOGLOBALENABLE = "extensions.swaksmack.audio.global_enable_boolpref";
const SMACK_AUDIOSOUND_OUTWIT = "extensions.swaksmack.audio.outwitsound_stringpref";

const SMACK_AUDIOSOUND_OUTWITVOTE = "extensions.swaksmack.audio.outwitvotesound_stringpref";
const SMACK_AUDIOSOUND_OUTWITPOINT = "extensions.swaksmack.audio.outwitpointsound_stringpref";
const SMACK_AUDIOSOUND_OUTWITRESULT = "extensions.swaksmack.audio.outwitresultsound_stringpref";
const SMACK_AUDIOSOUND_SMACKPOTBET = "extensions.swaksmack.audio.smackpotsound_stringpref";
const SMACK_AUDIOSOUND_SMACKPOTWON = "extensions.swaksmack.audio.smackpotwonsound_stringpref";
const SMACK_AUDIOSOUND_GURUGUESS = "extensions.swaksmack.audio.gurusound_stringpref";
const SMACK_AUDIOSOUND_WHEELSPIN = "extensions.swaksmack.audio.wheelspinsound_stringpref";
const SMACK_AUDIOSOUND_PM = "extensions.swaksmack.audio.pmsound_stringpref";
const SMACK_AUDIOSOUND_LR = "extensions.swaksmack.audio.lrsound_stringpref";
const SMACK_AUDIOSOUND_CHATKEYWORD = "extensions.swaksmack.audio.chatkeywordsound_stringpref";
const SMACK_AUDIOSOUND_CHATUSERNAME = "extensions.swaksmack.audio.chatusernamesound_stringpref";
const SMACK_AUDIOSOUND_ITEMSOLD = "extensions.swaksmack.audio.itemsoldsound_stringpref";
const SMACK_AUDIOSOUND_OUTWITCONTESTANT = "extensions.swaksmack.audio.outwitcontestantsound_stringpref";


const SMACK_CHECKPMCHAT = "extensions.swaksmack.pmchatcheck_boolpref1";
const SMACK_ENHANCEDCHATUI = "extensions.swaksmack.enhancedChatUI_boolpref";
const SMACK_ENHANCEDCHATUIICONS = "extensions.swaksmack.enhancedChatUIIcons_boolpref";
const SMACK_ENHANCEDLARGEAVATARS = "extensions.swaksmack.enhancedlargeavatars_boolpref";
const SMACK_ENHANCEHIDEAVATARS = "extensions.swaksmack.enhancedHideAvatars_boolpref";
const SMACK_SBSALEINTERVAL = "extensions.swaksmack.statusbarsaleinterval_intpref";
const SMACK_DISPLAYPMSTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarpm_boolpref1";
const SMACK_DISPLAYLRSTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarlr_boolpref1";
const SMACK_DISPLAYKWSTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarkw_boolpref1";
const SMACK_DISPLAYSALESTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarsale_boolpref1";
const SMACK_DISPLAYTITLEINFO = "extensions.swaksmack.appearance.displaytitleinfo_boolpref1";
const SMACK_DISPLAYLARGEAVATAR = "extensions.swaksmack.appearance.displaylargeavatar_boolpref1";
const SMACK_DISPLAYAVATARSIZE = "extensions.swaksmack.appearance.largeavatar_msize_intpref1";
const SMACK_DISPLAYSOLDINFO = "extensions.swaksmack.appearance.displaysoldinfo_boolpref1";
const SMACK_DISPLAYOTSINFO = "extensions.swaksmack.appearance.displayotsinfo_boolpref1";
const SMACK_DISPLAYEHANCEDOTSINFO="extensions.swaksmack.appearance.displayenhancedotsinfo_boolpref1";
const SMACK_DISPLAYHIDDENBADGES = "extensions.swaksmack.appearance.displayhiddenbadges_boolpref1";
const SMACK_DISPLAYCONVERTLT = "extensions.swaksmack.appearance.displayconvertlessthan_boolpref1";
const SMACK_DISPLAYBBCODEPOSTS = "extensions.swaksmack.appearance.displaybbcodeposts_boolpref1";
const SMACK_DISPLAYBBCODEREMOVETAGS = "extensions.swaksmack.appearance.removebbcodetags_boolpref1";
const SMACK_TINYURLENABLE = "extensions.swaksmack.tinyurl_enable_boolpref1";
const SMACK_TINYURLLENGTH = "extensions.swaksmack.tinyurl_maxurllength_intpref";
const SMACK_REPLYPREFIX = "extensions.swaksmack.replyprefix_stringpref";
const SMACK_REPLYSUFFIX = "extensions.swaksmack.replysuffix_stringpref";
const SMACK_AUTOREPLYHIGHLIGHT = "extensions.swaksmack.autoreplyhighlight_boolpref";
const SMACK_AUTOREPLYTIMEOUT = "extensions.swaksmack.autoreplytime_intpref";
const SMACK_TINYURLPREVIEW = "extensions.swaksmack.tinyurl_enablepreview_boolpref";
const SMACK_ALERTGLOABLEENABLE = "extensions.swaksmack.alerts.global_enable_boolpref";
const SMACK_URL_SPAMWARN = "extensions.swaksmack.url.spamwarn_boolpref1";

const SMACK_IGNOREAVATARLIST = "extensions.swaksmack.appearance.ignoreavatarlist_stringpref";
const SMACK_IGNOREAVATARPIC = "extensions.swaksmack.appearance.ignoreavatarpic_stringpref";
const SMACK_IGNOREALLAVATARS = "extensions.swaksmack.appearance.ignoreallavatars_boolpref1";


const SMACK_CHECKPMINTERVAL = "extensions.swaksmack.options.pmcheckinterval_intpref";
const SMACK_MINPMPOLLINTERVAL = "extensions.swaksmack.options.minpmcheckinterval_intpref";


const SMACK_STAT_COLLECT = "extensions.swaksmack.stats.collectstats_boolpref1";
const SMACK_STAT_OW_OPTINCOUNT = "extensions.swaksmack.stats.outwitoptin_intpref";
const SMACK_STAT_OW_SELECTED = "extensions.swaksmack.stats.outwitselected_intpref";
const SMACK_STAT_OW_VOTECOUNT = "extensions.swaksmack.stats.outwitvoted_intpref";
const SMACK_STAT_OW_POINTCOUNT = "extensions.swaksmack.stats.outwitpoints_intpref";
const SMACK_STAT_OW_WINCOUNT = "extensions.swaksmack.stats.outwitwon_intpref";
const SMACK_STAT_SP_PLAYED = "extensions.swaksmack.stats.smackpotplayed_intpref";
const SMACK_STAT_SP_COINBETCOUNT = "extensions.swaksmack.stats.smackpotcoinsguessed_intpref";
const SMACK_STAT_SP_COINWONCOUNT = "extensions.swaksmack.stats.smackpotcoinswon_intpref";
const SMACK_STAT_GG_PLAYED = "extensions.swaksmack.stats.guruguessplayed_intpref";
const SMACK_STAT_OW_MAXLISTSIZE = "extensions.swaksmack.stats.ots.maxlistsize_intpref";

// These could be defaults to fill a user config list
const SEARCH_FROOGLE_URL = "http://www.google.com/products?q=SMACK_PROD";
const SEARCH_SMACKOSHAME_URL = "http://smackofshame.com/archives.html?q=SMACK_PROD"
const SEARCH_AMAZON_URL = "http://www.amazon.com/exec/obidos/external-search?mode=blended&keyword=SMACK_PROD"
const SEARCH_EBAY_URL = "http://search.ebay.com/search/search.dll?MfcISAPICommand=GetResult&ht=1&SortProperty=MetaEndSort&query=SMACK_PROD";

//break the prefs into option items groups
//these grouping will allow the reseting of different categories (e.g. ignore, audio,etc)
var SMACK_OPTIONITEMS = [SMACK_AUTOURL,SMACK_EASYURL,SMACK_MAXURL,SMACK_MAXLENGTH,SMACK_ALTALERTMONITOR,SMACK_ENABKEALERTMONITORDELAY,
SMACK_TRUNCURL,SMACK_OUTWITALERT,SMACK_OUTWITVOTEALERT,SMACK_OUTWITRANDOM,SMACK_GURUGUESSALERT,SMACK_SMACKPOTALERT,SMACK_BLOCKWILDCARD,
SMACK_CHECKPMCHAT,SMACK_CHECKPMINTERVAL,SMACK_MINPMPOLLINTERVAL,SMACK_ENHANCEDCHATUI,SMACK_TINYURLENABLE,SMACK_TINYURLLENGTH,
SMACK_SBSALEINTERVAL,SMACK_ENHANCEDCHATUIICONS,SMACK_ENHANCEDLARGEAVATARS,SMACK_ENHANCEHIDEAVATARS,SMACK_REPLYPREFIX,SMACK_REPLYSUFFIX,
SMACK_TINYURLPREVIEW,SMACK_ALERTGLOABLEENABLE,SMACK_AUTOREPLYHIGHLIGHT,SMACK_AUTOREPLYTIMEOUT,SMACK_URL_SPAMWARN
];

var SMACK_HIGHLIGHT_OPTIONITEMS =[SMACK_GLOBAL_ENABLEHL,SMACK_HL_ENABLEJFEMPLOYEE,SMACK_IGNORECASEHL,SMACK_IGNORESPHL,
SMACK_ENABLELRHL,SMACK_HL_DYNUNOPT,SMACK_HL_DYNKWOPT,SMACK_HL_JFEMPLOYEEOPT,
SMACK_ENABLEHL1,SMACK_KEYWORDHL1,SMACK_USERNAMEONLYHL1,SMACK_OUTLINEHL1,SMACK_USERNAMEHL1,SMACK_CHATWILDCARD1,
SMACK_TCHL1,SMACK_BTCHL1,SMACK_UNDERLINEHL1,SMACK_ITALICHL1,SMACK_BOLDHL1,SMACK_WORDONLYHL1,SMACK_CHATINFOHL1,
SMACK_ENABLEHL2,SMACK_KEYWORDHL2,SMACK_USERNAMEONLYHL2,SMACK_OUTLINEHL2,SMACK_USERNAMEHL2,SMACK_CHATWILDCARD2,
SMACK_TCHL2,SMACK_BTCHL2,SMACK_UNDERLINEHL2,SMACK_WORDONLYHL2,SMACK_CHATINFOHL2,
SMACK_ENABLEHL3,SMACK_KEYWORDHL3,SMACK_USERNAMEONLYHL3,SMACK_OUTLINEHL3,SMACK_USERNAMEHL3,SMACK_CHATWILDCARD3,
SMACK_TCHL3,SMACK_BTCHL3,SMACK_UNDERLINEHL3,SMACK_WORDONLYHL3,SMACK_CHATINFOHL3
];

var SMACK_THEME_OPTIONITEMS = [SMACK_THEME_CHATTC,SMACK_THEME_CHATBTC,SMACK_THEME_ENABLE,SMACK_THEME_CHATNICK,
SMACK_THEME_CHATGURU,SMACK_THEME_CHATTIME,SMACK_THEME_CHATACTIONS,SMACK_THEME_CHATLINKS,SMACK_THEME_BKGRD,
SMACK_THEME_CURRENTTHEME
];

var SMACK_IGNORE_OPTIONITEMS = [SMACK_ENABLEIGNORE1,SMACK_IGNORELIST1,SMACK_IGNORELIST2,
SMACK_IGNORELISTATTEND,SMACK_FUNIGNORE1,SMACK_ENABLE_FUNLIST,SMACK_FUNLIST_FILE,
SMACK_ENABLECAPSUPRESSION,SMACK_CAPSTHESHOLD,SMACK_ENABLE_FUNAVATAR,SMACK_ENABLE_NOOBIGNORE,
SMACK_NOOBIGNORE_THRESHOLD
];

var SMACK_ADV_OPTIONITEMS = [SMACK_CHATSPEED,SMACK_DEBUGENABLED,SMACK_DEBUGINFO
];

var SMACK_AUDIO_OPTIONITEMS = [SMACK_AUDIOSOUND_OUTWIT,SMACK_AUDIOGLOBALENABLE,SMACK_AUDIOSOUND_OUTWITVOTE,
SMACK_AUDIOSOUND_OUTWITPOINT,SMACK_AUDIOSOUND_SMACKPOTBET,SMACK_AUDIOSOUND_SMACKPOTWON,SMACK_AUDIOSOUND_GURUGUESS,
SMACK_AUDIOSOUND_WHEELSPIN,SMACK_AUDIOSOUND_PM,SMACK_AUDIOSOUND_LR,SMACK_AUDIOSOUND_CHATKEYWORD,SMACK_AUDIOSOUND_CHATUSERNAME,
SMACK_AUDIOSOUND_ITEMSOLD,SMACK_AUDIOSOUND_OUTWITCONTESTANT,SMACK_AUDIOSOUND_OUTWITRESULT
];

var SMACK_APPEARANCE_OPTIONITEMS = [
SMACK_DISPLAYPMSTATUSBAR,SMACK_DISPLAYLRSTATUSBAR,SMACK_DISPLAYKWSTATUSBAR,SMACK_DISPLAYSALESTATUSBAR,SMACK_DISPLAYTITLEINFO,
SMACK_DISPLAYLARGEAVATAR,SMACK_DISPLAYAVATARSIZE,SMACK_DISPLAYSOLDINFO,SMACK_DISPLAYOTSINFO,SMACK_DISPLAYHIDDENBADGES,SMACK_DISPLAYEHANCEDOTSINFO,
SMACK_DISPLAYCONVERTLT,SMACK_IGNOREAVATARLIST,SMACK_IGNOREAVATARPIC,SMACK_IGNOREALLAVATARS, SMACK_DISPLAYBBCODEPOSTS,SMACK_DISPLAYBBCODEREMOVETAGS
];

var SMACK_STATS_OPTIONITEMS = [SMACK_STAT_COLLECT,SMACK_STAT_OW_OPTINCOUNT,SMACK_STAT_OW_SELECTED,SMACK_STAT_OW_VOTECOUNT,SMACK_STAT_OW_POINTCOUNT,
SMACK_STAT_OW_WINCOUNT,SMACK_STAT_SP_PLAYED,SMACK_STAT_SP_COINBETCOUNT,SMACK_STAT_SP_COINWONCOUNT,SMACK_STAT_GG_PLAYED.SMACK_STAT_OW_MAXLISTSIZE
];

//div ids used to find outwit opt in and answer elements
const SMACK_COMMENTTEXT = "commentText";
const SMACK_COMMENTNICK = "chatNick";
const SMACK_COMMENTAVATAR = "chatAvatarContainer";
const SMACK_OUTWITCOMMENTDIV = "comment_comment";
const SMACK_PMDIV = "messagesContainer";
const SMACK_OUTWITCAPDIV = "captchaBox";
const SMACK_OUTWITANSWERDIV = "outwitAnswer";
const SMACK_OUTWITGURUGUESSDIV = "guruMakeGuess";
const SMACK_DEALDIV = "deal";
const SMACK_OUTWITCONDIV = "outwitContainer";
const SMACK_GURUCONDIV = "guruContainer";
//needed???
const SMACK_SHOWNAMEVALUE = "showName";
const SMACK_SHOWNAMEDIV = "The Daily Smack with Smack Daddy";

const SMACK_ALERT_CUSTOM = -1;
const SMACK_ALERT_OUTWITOPTIN = 1;
const SMACK_ALERT_OUTWITVOTE = 2;
const SMACK_ALERT_GURUGUESS = 10;
const SMACK_ALERT_SMACKPOTGUESS = 20;
const SMACK_ALERT_BUYALERT = 30;
const SMACK_ALERT_GURUWHEELSPIN = 40;


const SWAKCOMMENTINFO = ".//*[contains(concat(' ', @class, ' '), ' commentInfo ')]";
const SWAKCHATPOST = ".//*[contains(concat(' ', @class, ' '), ' chatPost ')]";
const SWAKCHATNICK = ".//*[contains(concat(' ', @class, ' '), ' chatNick ')]";
const SWAKCHATGURU = ".//*[contains(concat(' ', @class, ' '), ' chatGuru ')]";
const SWAKCHATAVATARCONTAINER = ".//*[contains(concat(' ', @class, ' '), ' chatAvatarContainer ')]";
const SWAKCHATAVATAR = ".//*[contains(concat(' ', @class, ' '), ' chatAvatar ')]";
const SWAKCOMMENTTEXT = ".//*[contains(concat(' ', @class, ' '), ' commentText ')]";
const SWAKLARGEBADGE = ".//*[contains(concat(' ', @class, ' '), ' largeBadge ')]";
const SWAKSMACKHIGHLIGHTUSER = ".//*[contains(concat(' ', @class, ' '), ' swaksmackHighlightUser ')]";
const SWAKSMACKUNHIGHLIGHTUSER = ".//*[contains(concat(' ', @class, ' '), ' swaksmackUnhighlightUser ')]";


//var SS_chatcss = "@namespace url(http://www.w3.org/1999/xhtml);  /* Change color of  links */ #chat div.commentText a:visited, #chat div.commentText a:link { color: #FF7800 !important; } ";

var SS_chatcss = "@namespace url(http://www.w3.org/1999/xhtml);  /* Change color of  links */ #chat div.commentText a:visited, #chat div.commentText a:link { color: #FF7800 !important; } a.swaksmackReply { color: #FF7800 !important; font-size: 11px;} a.swaksmackHighlightUser, a.swaksmackUnhighlightUser {color: #FFBC80 !important; font-size: 11px;}  ";


var SS_chatHeaderChange = false;



var SS_ggListenerAdded = false;
var SS_keywordDisplayLength = 15;

var SS_window;


var SS_dynamicKeywords = new Array();


var SS_dynamicUsernames = new Array();

var SS_colorCommentMatchArray = new Array();
var SS_ChatHeaderText = null;
var SS_UID;
var SS_ggcalc;
var SS_GGCalcWindow;

var tinyurlpreviewregex = /tinyurl\.com\/(.*)/i;

const JF_HL_replacement = "\u0009\(\[^\u0009\]*\)\u0009";
var JF_HL_repRegEx = new RegExp(JF_HL_replacement,"g");
const JF_taggedMatches = "\u0009$1\u0009";
const JF_pass2replace = "$1";

var JF_HTMLBadPost_RegExp = new RegExp("(<|&lt;|\\u227a).*(script|object|applet|embed|href|on\\w{1,}\\s*=)","ig");
//var JF_HTMLTag_regExp = new RegExp("</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?>","ig");
var JF_HTMLTag_regExp = new RegExp("(<|&lt;|\\u227a)/?(img|h\\d+|strong|small|big|b|i|u|font|br|ul|ol|li)((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?>","ig");
//var JF_BBCODETag_RegExp = new RegExp("","ig");
var JF_BBCODETag_RegExp = new RegExp("\\[/?(img|b|i|u|size|br|color|code|email|url|s|quote)((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?\\]","ig");

//ignore list
var JF_ignoreUserlistRegExp = null;
var JF_ignoreWordlistRegExp = null;
var JF_ignoreAttendancelistRegExp = null;
var JF_ignoreAvatarlistRegExp = null;

//highlight lists
//var JF_keywordlistRegExp = null;
//var JF_usernamelistRegExp = null;

var JF_usernameArray = new Array();
var JF_keywordArray = new Array();
var JF_usernameHLIgnoreArray = new Array();
var JF_keywordHLIgnoreArray = new Array();

var SwakChatThemeRegEx = new RegExp("([^,|]*),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6})","ig");
var SwakChatThemeColorsRegExStr = ",(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6}),(#[0-9a-f]{6})";
var SwakURLSpamWarnRegEx = new RegExp("(http:\/\/)?(www[.])?(internetisseriousbusiness.com|tinyurl.com/2nmscj)","ig");

var swakOTSList = new Array();
var swakOTSListIndex = 0;
var swakOTSInnerHtml = null;
var swakSoldInnerHtml = null;
var swakSmackPotSoldInnerHtml = null;
var swakGuruWinnersInnerHtml = null;
var swakHighlightReplyUser = null;
var swakHighlightReplyMap = null;
var swakHighlightReplyId = -1;
var swakException = null;
var swakExceptionList = new Array();
var swakOTSEvalCount = 0;


var bbsearch = new Array(
          /\[img\](.*?)\[\/img\]/,
          /\[url=([\w]+?:\/\/[^\\\"\n\r\t<]*?)\](.*?)\[\/url\]/,
          /\[url\]((www|ftp|)\.[^\\\"\n\r\t<]*?)\[\/url\]/,
          /\[url=((www|ftp|)\.[^ \\\"\n\r\t<]*?)\](.*?)\[\/url\]/,
          /\[email\](([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)?[\w]+))\[\/email\]/,
          /\[b\](.*?)\[\/b\]/,
          /\[u\](.*?)\[\/u\]/,
          /\[i\](.*?)\[\/i\]/,
          /\[code\](.*?)\[\/code\]/,
          /\[color=(.*?)\](.*?)\[\/color\]/,
          /\[s\](.*?)\[\/s\]/,
          /\[size=(.*?)\](.*?)\[\/size\]/,
          /\[quote=(.*?)\](.*?)\[\/quote\]/,
          /\[url\](http:\/\/[^\n\r\t\"\\<]*?)\[\/url\]/);

var bbreplace = new Array(
          "<img src=\"$1\" alt=\"An image\"/>",
          "<a href=\"$1\" target=\"blank\">$2</a>",
          "<a href=\"http://$1\" target=\"blank\">$1</a>",
          "<a href=\"$1\" target=\"blank\">$1</a>",
          "<a href=\"mailto:$1\">$1</a>",
          "<b>$1</b>",
          "<u>$1</u>",
          "<i>$1</i>",
          "<code>$1</code>",
          "<span style=\"color:$1\">$2</span>",
          "<span style=\"text-decoration: line-through;\">$1</span>",
          "<span style=\"font-size: $1px;\">$2</span>",
          "$1 wrote: $2",
          "<a href=\"$1\" target=\"blank\">$1</a>");
          
var bbtagremove = new Array(
          "$1",
          "$1",
          "$1",
          "$1",
          "$1",
          "$1",
          "$1",
          "$1",
          "$1",
          "$2",
          "$1",
          "$2",
          "$2",
          "$1");          

function SwakChatTheme() {
	this.name = null;
	this.chatBkgrd = null;
	this.chatText = null;
	this.chatNick = null;
	this.chatGuru = null;
	this.chatTime = null;
	this.chatActions = null;
	this.chatLinks = null;
	this.cBkgrd = null;
}

function buildSwakChatThemes(themeString) {
	if (themeString == null) return null;
	//var search = "([^,|]*)" + SwakChatThemeColorsRegExStr;
	//alert('search string ' + search);
	//var themeRE = new RegExp(search,"i");
	var matches = null;
	var result = new Array();
	while((matches = SwakChatThemeRegEx.exec(themeString)) != null) {   //while ((matches = oRegExp.exec(inputText)) != null)
		if (matches == null) continue;	
		//alert('matches: ' + matches);
		var chatTheme = new SwakChatTheme();
		chatTheme.name = matches[1];
		chatTheme.chatBkgrd = matches[2];
		chatTheme.chatText = matches[3];
		chatTheme.chatNick = matches[4];
		chatTheme.chatGuru = matches[5];
		chatTheme.chatTime = matches[6];
		chatTheme.chatActions = matches[7];
		chatTheme.chatLinks = matches[8];
		chatTheme.cBkgrd = matches[9];
		result.push(chatTheme);
		//alert('results array length ' + result.length);
	}
	
	return result;
}


function buildSwakChatTheme(themeName, themeString) {
	if (themeName == null || themeString == null) return null;
	if (themeString.indexOf(themeName) == -1) return null;
	var search = themeName + SwakChatThemeColorsRegExStr;
	var themeRE = new RegExp(search,i);
	var matches = themeRE.exec(themeString);
	if (matches == null) return null;
	var chatTheme = new SwakChatTheme();
	chatTheme.name = themeName;
	chatTheme.chatBkgrd = matches[1];
	chatTheme.chatText = matches[2];
	chatTheme.chatNick = matches[3];
	chatTheme.chatGuru = matches[4];
	chatTheme.chatTime = matches[5];
	chatTheme.chatActions = matches[6];
	chatTheme.chatLinks = matches[7];
	chatTheme.cBkgrd = matches[8];
	return chatTheme;
}

function buildSwakThemeString(name,chatBkgrd,chatText,chatNick,chatGuru,chatTime,chatActions,chatLinks,cBkgrd) {
	var themeString = name;
	themeString += ',';
	themeString += chatBkgrd;
	themeString += ',';
	themeString += chatText;
	themeString += ',';
	themeString += chatNick;
	themeString += ',';
	themeString += chatGuru;
	themeString += ',';
	themeString += chatTime;
	themeString += ',';
	themeString += chatActions;	
	themeString += ',';
	themeString += chatLinks;
	themeString += ',';
	themeString += cBkgrd;	
	themeString += '|';
	return themeString;	
}

function buildSwakThemeStringFromObject(chatTheme) {
	if (chatTheme == null ) return '';
	var themeString = chatTheme.name;
	themeString += ',';
	themString += chatTheme.chatBkgrd;
	themeString += ',';
	themString += chatTheme.chatText;
	themeString += ',';
	themString += chatTheme.chatNick;
	themeString += ',';
	themString += chatTheme.chatGuru;
	themeString += ',';
	themString += chatTheme.chatTime;
	themeString += ',';
	themString += chatTheme.chatActions;	
	themeString += ',';
	themString += chatTheme.chatLinks;	
	themeString += ',';
	themString += chatTheme.cBkgrd;		
	themeString += '|';
	return themeString;	
}

function checkHost(doc) {
    if (doc==null)
        return false; 
	host = doc.location.host;
	//alert(host);
	if (host == 'www.jellyfish.com' || host == 'jellyfish.com' || host==null || host=='')
	return true;
	return false;
}

function isPMArea(doc) {

	if (doc == null) doc=content.document;
	var hostPath = doc.location.pathname;
	var matches = hostPath.match("/shoppers/me/messages");
	if (matches != null) {
		return true;
	}
	return false;
}

function isSmackShopArea(doc) {
	if (doc == null) doc = content.document;
	var hostPath = doc.location.pathname;
	var matches = hostPath.match("/smacktv/channel");
	if (matches != null) {
		return true;
	}
	return false;
}

function isLRArea(doc) {
	if (doc == null) doc = content.document;
	var lrDiv = doc.getElementById('livingRoomName');
	if (lrDiv != null) return true;
	return false;
}

function applyPMCSS(doc) {
	if (doc == null) doc = content.document;
	var heads = doc.getElementsByTagName("head");
	if (heads.length > 0) {
		var node = doc.createElement("link");
		node.href="chrome://swaksmack/skin/swaksmackpm.css";
		//node.innerHTML = SS_chatcss;
		node.type = "text/css";
		node.rel="Stylesheet";
		heads[0].appendChild(node);
	}
}

function chatLinkColor(doc) {
	if (doc == null) doc = content.document;
	var heads = doc.getElementsByTagName("head");
	if (heads.length > 0) {
		/*
		var node = doc.createElement("style");
		///	node.href="chrome://swaksmack/skin/swaksmack.css";
		node.innerHTML = SS_chatcss;
		node.type = "text/css";
		heads[0].appendChild(node);
		*/
		var node = doc.createElement("link");
		node.href="chrome://swaksmack/skin/swaksmack.css";
		//node.innerHTML = SS_chatcss;
		node.type = "text/css";
		node.rel="Stylesheet";
		heads[0].appendChild(node);
	}
}
//from http://robertnyman.com/js/getElementsByClassName.js
function getElementsByClassName_ORG(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

function _getElementsByXPath(expression,parent,ownerNode) {
	try {
	if (ownerNode == null) ownerNode = content.document; 
	var results = [];
	var query = ownerNode.evaluate(expression, parent || window.content.document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	for (var i = 0, length = query.snapshotLength; i < length; i++)
	results.push(query.snapshotItem(i));
	return results;
} catch(x) {
//alert(x + ' ' + expression);
}
}

function getElementsByClassName(className,parent,doc) {
	var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
	return _getElementsByXPath(q,parent,doc);
}

function getElementCommentInfo(parent,doc) {
	return _getElementsByXPath(SWAKCOMMENTINFO,parent,doc);
}

function getElementChatPost(parent,doc) {
	return _getElementsByXPath(SWAKCHATPOST,parent,doc);
}

function getElementChatNick(parent,doc) {
	return _getElementsByXPath(SWAKCHATNICK,parent,doc);
} 

function getElementChatGuru(parent,doc) {
	return _getElementsByXPath(SWAKCHATGURU,parent,doc);
} 

function getElementChatAvatarContainer(parent,doc) {
	return _getElementsByXPath(SWAKCHATAVATARCONTAINER,parent,doc);
}

function getElementChatAvatar(parent,doc) {
	return _getElementsByXPath(SWAKCHATAVATAR,parent,doc);
}

function getElementCommentText(parent,doc) {
	return _getElementsByXPath(SWAKCOMMENTTEXT,parent,doc);
}

function getElementLargeBadge(parent,doc) {
	return _getElementsByXPath(SWAKLARGEBADGE,parent,doc);
}

function getElementSwakHighlightUser(parent,doc) {
	return _getElementsByXPath(SWAKSMACKHIGHLIGHTUSER,parent,doc);
}

function getElementSwakUnhighlightUser(parent,doc) {
	return _getElementsByXPath(SWAKSMACKUNHIGHLIGHTUSER,parent,doc);
}

function buildClassNameRegex(strClassName) {
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	return oRegExp;
}

function buildSearchString_ORG(searchArray, wordBoundary) {
	if(wordBoundary == null) wordBoundary = true;
	var searchreg = null;
	if (searchArray == null || searchArray.length == 0) return '';
	for (var i=0; i<searchArray.length;i++){
		if (searchArray[i] == null || searchArray[i]== "") continue;
		if (searchreg == null) {
			var trimmed = searchArray[i].replace(/^\s+|\s+$/g, '') ;
			searchreg = SS_escapeRegExLiterals(trimmed);
			//searchreg = SS_escapeRegExLiterals(searchArray[i].trim());
			if(wordBoundary) {
				var glob = /\\\*$/.test(searchreg);
				if (!glob) {
					searchreg = '\\b'+searchreg+'\\b';
					//alert('exact match ' + searchreg);
				}
				else {
					//replace \*
					searchreg = searchreg.replace(/\\\*$/,'');
				}
			}
			if (searchreg == '')
			searchreg = null;
			continue;
		}
		var trimmed = searchArray[i].replace(/^\s+|\s+$/g, '') ;
		var str = SS_escapeRegExLiterals(trimmed);
		if(wordBoundary) {
			var glob = /\\\*$/.test(str);
			if (!glob) {
				str = '\\b' + str + '\\b';
			}
			else {
				str = str.replace(/\\\*$/,'');
			}
		}
		if (str != null && str != '')
		searchreg = searchreg + '|' + str;
	}
	return searchreg;
}


function buildSearchString(searchArray, wordBoundary) {
	if(wordBoundary == null) wordBoundary = true;
	var searchreg = null;
	if (searchArray == null || searchArray.length == 0) return '';
	for (var i=0; i<searchArray.length;i++){
		if (searchArray[i] == null || searchArray[i]== "") continue;
		if (searchreg == null) {
			var trimmed = searchArray[i].replace(/^\s+|\s+$/g, '') ;
			searchreg = SS_escapeRegExLiterals(trimmed);
			//searchreg = SS_escapeRegExLiterals(searchArray[i].trim());
			if(wordBoundary) {
				var glob = /\\\*$/.test(searchreg);
				if (!glob) {
					searchreg = '(\\s+|^|\\W)'+searchreg+'(\\s+|$|\\W)';
//2					searchreg = '(\\s+|^)'+searchreg+'(\\s+|$)';
					//alert('exact match ' + searchreg);
				}
				else {
					//replace \*
					searchreg = searchreg.replace(/\\\*$/,'');
				}
			}
			if (searchreg == '')
			searchreg = null;
			continue;
		}
		var trimmed = searchArray[i].replace(/^\s+|\s+$/g, '') ;
		var str = SS_escapeRegExLiterals(trimmed);
		if(wordBoundary) {
			var glob = /\\\*$/.test(str);
			if (!glob) {
				str = '(\\s+|^|\\W)' + str + '(\\s+|$|\\W)';
//2				str = '(\\s+|^)' + str + '(\\s+|$)';
			}
			else {
				str = str.replace(/\\\*$/,'');
			}
		}
		if (str != null && str != '')
		searchreg = searchreg + '|' + str;
	}
	return searchreg;
}

//http://4umi.com/web/javascript/array.htm#unique

function getUniqueArray(sourceArray,b) {
	var a = [], i, l = sourceArray.length;
	for( i=0; i<l; i++ ) {
		if( a.indexOf( sourceArray[i], 0, b ) < 0 ) { a.push( sourceArray[i] ); }
	}
	return a;
}


function highlightExistingComments(doc) {
	if (doc == null) return;
	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
	if (cm == null) return;
	for (var i=0;i<cm.length;i++) {
		var comment = 'comment' + cm[i];
		var chatComment = doc.getElementById(comment);
		commentColor(chatComment,doc);
	}
}



function highlightExistingUsernames(doc, username,highlightclass) {
	if (doc == null) return;
	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
	if (cm == null) return;
	for (var i=0;i<cm.length;i++) {
		var comment = 'comment' + cm[i];
		var chatComment = doc.getElementById(comment);
		//commentColor(chatComment,doc);
		updateHighlightLinks(doc,username,chatComment,highlightclass);

	}
}

function toggleHighlightedCommentDisplay(doc,hidden) {
	if (doc == null || hidden == null) return;
	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
	if (cm == null) return;
	for (var i=0;i<cm.length;i++) {
		var comment = 'comment' + cm[i];
		var chatComment = doc.getElementById(comment);
		if (hidden == true) {
			//don't hide highlighted comments
			var sunhl = chatComment.getAttribute('swaksmackusernamehighlighted');
			var skhl = chatComment.getAttribute('swaksmackkeywordhighlighted');
			if (sunhl == 'true' || skhl == 'true'){
				//alert('found comment to NOT hide');
				continue;
			}
			//chatComment.style.display='none';
			hideChatComment(chatComment, true);
		}
		else {
			hideChatComment(chatComment, false);
			//chatComment.style.display='inline';
		}
		//commentColor(chatComment,doc);

	}
}

function hideChatComment(chatComment, hide) {
	if (chatComment == null) return;
	if (hide == true) {
		chatComment.style.display='none';
	}
	else {
		chatComment.removeAttribute("style");
	}
}

function clearHighlightArrays() {
	JF_usernameArray = [];
	JF_keywordArray = [];
	JF_usernameHLIgnoreArray = [];
	JF_keywordHLIgnoreArray = [];
}

function commentEnhance(element, doc) {
	try {
	// alert(element.className + ' (cn) commentEnhance entry (id) ' +element.id);

	if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
		//alert('ce--lr return');
		return;
	}

	var jellyfishstrings = document.getElementById("swaksmack-strings");

	//	if (true) return;
	var commentInfo = getElementCommentInfo(element,doc);
	//var commentInfo = getElementsByClassName("commentInfo",element);
	var chatNick = getElementChatNick(commentInfo[0],doc);
	//var chatNick = getElementsByClassName('chatNick',commentInfo[0]);
	var postUserName = chatNick[0].textContent;

	//var usernames =SS_getPreference(SMACK_USERNAMEHL1);

	var unindex = SS_dynamicUsernames.indexOf(postUserName);   //was SS_combinedUsernames

	var tooltip = '';
	//alert('postUserName ' + postUserName + ' unindex ' + unindex);
	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){}

	var commentText = getElementsByClassName("commentText",element,doc);  //optimize
	//	var chatPost = getElementsByClassName("chatPost",element);
	var link = doc.createElement("a");
	if (unindex<0) {
		link.className='swaksmackHighlightUser';
		if (useImage) {
			link.innerHTML="<img src=\"chrome://swaksmack/skin/icons/highlighter.png\"/>";
		}
		else {
			link.textContent='Highlight';
		}
		tooltip = jellyfishstrings.getString("highlight_tooltip");
		link.title=tooltip;

	}
	else {
		link.className='swaksmackUnhighlightUser';
		if (useImage) {
			link.innerHTML="<img src=\"chrome://swaksmack/skin/icons/unhighlighter.png\"/>"; //class=\"swaksmackUnhighlightUser\"
		}
		else {
			link.textContent='Unhighlight';
		}
		tooltip = jellyfishstrings.getString("unhighlight_tooltip");
		link.title=tooltip;

	}
	link.target='_blank';
	link.href = '#';
	try{
		commentInfo[0].insertBefore(link,commentText[0]);
	}
	catch (x) {}

	link.addEventListener('click', enhancedHighlight,false);



	//insert a space
	var txtNode = doc.createTextNode(" ");
	try{
		commentInfo[0].insertBefore(txtNode,commentText[0]);
	}
	catch (x) {}

	var replylink = doc.createElement("a");
	replylink.className='swaksmackReply';
	if (useImage) {
		replylink.innerHTML="<img src=\"chrome://swaksmack/skin/icons/user_comment.png\"/>";
	}
	else {
		replylink.textContent=' Reply';
	}
	tooltip = jellyfishstrings.getString("reply_tooltip");
	replylink.title=tooltip;

	replylink.target='_blank';
	replylink.href = '#';
	try{
		//commentInfo[0].appendChild(link);
		commentInfo[0].insertBefore(replylink,commentText[0]);
	}
	catch (x) {}

	replylink.addEventListener('click', enhancedReply,false);
	
		//add "actions..."
	
  //insert a space
	txtNode = doc.createTextNode(" ");
	try{
		commentInfo[0].insertBefore(txtNode,commentText[0]);
	}
	catch (x) {}
	
	
	var actionlink = doc.createElement("a");
	actionlink.className='swaksmackAction';
	if (useImage) {
		actionlink.innerHTML="<img src=\"chrome://swaksmack/skin/icons/user_edit.png\"/>";
	}
	else {
		actionlink.textContent=' Actions';
	}
	tooltip = 'Actions';jellyfishstrings.getString("reply_tooltip");
	actionlink.title=tooltip;

	actionlink.target='_blank';
	actionlink.href = '#';
	try{
		commentInfo[0].insertBefore(actionlink,commentText[0]);
	}
	catch (x) {}
	
	actionlink.addEventListener('click', enhancedAction,false);
	
	//add large avatar mouse over
	if (SS_getPreference(SMACK_ENHANCEDLARGEAVATARS)) {
		var chatAvatar = getElementChatAvatar(element,doc);
		if (chatAvatar != null && chatAvatar[0] != null) {
			var cs = chatAvatar[0].getAttribute('src');
			var la = getLargeItemPhoto(chatAvatar[0]);
			var pn = chatAvatar[0].parentNode;
			//alert(pn.innerHTML);
	//		pn.innerHTML = pn.innerHTML + "<img class=\"preview\" src=\"" + la + "/>";
			pn.innerHTML = pn.innerHTML + "<div class=\"swakAvatarImageContainer\"> <img class=\"swakChatLargeAvatar\" src=\"" + la + "></div>";
			/*
			//REMOVE in favor of css method 010108
			//cs = cs.replace(/_m[.]jpg/,'.jpg');
			var foidiv = swaksmack.SmackShopDoc.createElement("div");
			var img = swaksmack.SmackShopDoc.createElement("img");
			img.className = 'swakChatLargeAvatar';
			img.setAttribute('src',la);
			//alert('img width ' + img.width + '   ' + img.height);
			foidiv.className='swakAvatarImageContainer';
			foidiv.style.height='0px';
			foidiv.style.width='0px';
			foidiv.appendChild(img);
		//	var cac = getElementChatAvatarContainer(element,doc);
			//cac[0].appendChild(foidiv);
			var cp = getElementChatPost(element,doc);
			cp[0].appendChild(foidiv);
			
			chatAvatar[0].addEventListener('mouseover',  function(event) {
										if (img.width == 0) {
											foidiv.style.height='1px';
											foidiv.style.width='1px';
										}
										else {
											var w = img.width+13;
											var h = img.height+13;
											foidiv.style.width=w + 'px';
											foidiv.style.height=h+  'px';
											
										}
										foidiv.style.overflow='visible';									
											}, false);
											
			chatAvatar[0].addEventListener('mouseout',  function(event) {
										foidiv.style.height='0px';
										foidiv.style.width='0px';
										foidiv.style.overflow='hidden';
										
											}, false);	
											*/
			
		}
	}

	commentInfo = null;
	commentText = null;
	chatNick = null;

}catch(xy) {
//alert(xy);
}

}

function enhancedAction(e) {
	e.stopPropagation();
	e.preventDefault();
	var actions = document.getElementById('swaksmackActions');
	document.popupNode = null;
	swaksmack.postPopupNode = null;
	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){}
	try {		
		
		//check is action is using an image
		if (useImage) {
			swaksmack.postPopupNode = e.target.parentNode.parentNode;
		}
		else {
			swaksmack.postPopupNode = e.target.parentNode;
		}
		//the anchor element needs to be some XUL element---so far this works
		actions.showPopup(document.getElementById('main-window'),e.screenX,e.screenY,"popup"); 

//weird--this works on one machine, but on another it on workd during a dblclick
	//	actions.showPopup(document.getElementById('swaksmackActions'),e.screenX,e.screenY,"popup"); 

	}
	catch (x) {
		swakAddException(x);
		alert('popup error ' + x);
	}
	
	
}

function enhancedHighlight(e) {
	e.stopPropagation();
	e.preventDefault();
	//alert('enhancedHighlight');
	//check is a username is selected and find that name
	if (findUsername() == true) {
		//name found...return
		e.target.focus();
		swakClearCurrentSelection();
		return;
	}
	swakClearCurrentSelection();

	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){}
	var highlightTarget = e.target;
	if (useImage) {
		highlightTarget = e.target.parentNode;
	}

	var ci = getCommentInfo(highlightTarget);


	//alert(pn.className + ' (org) --commentInfo element ' + ci.className);
	var chatNick = getElementChatNick(ci);
	//var chatNick = getElementsByClassName('chatNick',ci);
	var username = chatNick[0].textContent;

	var cn = highlightTarget.className;
	//highlightExistingUsernames(swaksmack.SmackShopDoc,username,cn);

	highlightExistingUsernames(content.document,username,cn);

	chatNick = null;

}



function findUsername(username) {
	var selectedName = '';
	if (username == null) {
		try {
			if (gContextMenu && gContextMenu.searchSelected) 
				selectedName = gContextMenu.searchSelected();
			else
				selectedName = getBrowserSelection();
		}
		catch (x) {return false;}
		if (selectedName == null || selectedName.length == 0) {
			return false;
		}
	}
	else {
		selectedName = username;
	}
	//now search posts for name
	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
	if (cm == null) return false;
	var nameRE = new RegExp(selectedName,"i");
	//alert('selectedName nameRE ' + nameRE);
	var found = false;
	for (var i=0;i<cm.length;i++) {
		nameRE.lastIndex = 0;
		var comment = 'comment' + cm[i];
		var chatComment = swaksmack.SmackShopDoc.getElementById(comment);
		if (chatComment == null) continue;
		var chatNick = getElementChatNick(chatComment);
		//var chatNick = getElementsByClassName('chatNick',chatComment);
		if (chatNick == null || chatNick[0] == null) continue;
		var possibleMatch = nameRE.test(chatNick[0].textContent);
		//alert('findUsername chatNick[0] ' + chatNick[0]);
		if (possibleMatch == true) {
			//alert('found user ' + chatNick[0]);
			found = true;
			highlightUsername(chatComment,swaksmack.SmackShopDoc);
		}
	}
	//return found;
	return true;
	
}

function updateHighlightLinks(doc,username, chatComment, highlightclass) {
	//alert('UHL');
	if (doc == null|| username == null || chatComment == null || highlightclass == null) return;
	if (SS_getPreference(SMACK_GLOBAL_ENABLEHL) == false) return;


	//var ci = getElementsByClassName('commentInfo',chatComment);
	var htarget = getElementsByClassName(highlightclass,chatComment,doc);

	var jellyfishstrings = document.getElementById("swaksmack-strings");
	var tooltip = '';
	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){}
	var highlightTarget = htarget[0];
	var chatNick = getElementChatNick(chatComment,doc);
	var postusername = chatNick[0].textContent;
	if (username != postusername) return;

	var cn = highlightclass;
	if (cn == 'swaksmackHighlightUser') {
		highlightTarget.className='swaksmackUnhighlightUser';
		if (useImage) {
			highlightTarget.innerHTML="<img src=\"chrome://swaksmack/skin/icons/unhighlighter.png\"/>";
		}
		else {
			highlightTarget.textContent='Unhighlight';
		}
		tooltip = jellyfishstrings.getString("unhighlight_tooltip");
		highlightTarget.title=tooltip;


		addUserNameToDynamicHL(username);

		if (SS_getPreference(SMACK_GLOBAL_ENABLEHL) == true) {
			highlightUsername(chatComment,doc);
		}
	}
	else if (cn == 'swaksmackUnhighlightUser'){
		highlightTarget.className='swaksmackHighlightUser';
		if (useImage) {
			highlightTarget.innerHTML="<img src=\"chrome://swaksmack/skin/icons/highlighter.png\"/>";
		}
		else {
			highlightTarget.textContent='Highlight';
		}
		tooltip = jellyfishstrings.getString("highlight_tooltip");
		highlightTarget.title=tooltip;
		unhighlightUsername(chatComment,doc);

		removeUserNameFromDynamicHL(username);

	}

	chatNick = null;
}


function enhancedReply(e) {
	//alert('enhanced reply ' + e.target);
	e.stopPropagation();
	e.preventDefault();

	try {
		var useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);

		var replyTarget = e.target;
		if (useImage) {
			replyTarget = e.target.parentNode;
		}

		var ci = getCommentInfo(replyTarget);
		var chatNick = getElementChatNick(ci);
		var username = chatNick[0].textContent;
		var chatPrefix ='';
		if (chatNick != null && chatNick[0] != null) {
			//alert( ' reply to ' + username);
			var cpost = content.document.getElementById('comment_comment');
			var replyText = getBrowserSelection();

			if (replyText != null && replyText.length>0) {
				replyText = "\""+replyText+"\"";
			}
			else {
				replyText = '';
			}


			cpost.value = buildReply(username,replyText);
			cpost.focus();
			swakClearCurrentSelection();
///TEST 113007
			if (SS_getPreference(SMACK_AUTOREPLYHIGHLIGHT) == true) {
				swakHighlightReplyUser = username;
			}
			
///



		}
	}
	catch(x){
		swakAddException(x);
	}
}

function swakClearCurrentSelection() {
	if (swaksmack.smackShopContentWindow == null) return;
	try {
		var s = swaksmack.smackShopContentWindow.getSelection();
		if(s.rangeCount > 1) {
		 for(var i = 1; i < s.rangeCount; i++) {
		  s.removeRange(s.getRangeAt(i));
		 }
		}
	}
	catch(x) {
		swakAddException('swakClearCurrentSelection ' +x);
	}
}

function previewTinyURL(element, doc, turl, commentDiv) {
	//alert(' previewTinyURL ' + element.textContent);
	if (element == null || doc == null || turl == null || commentDiv == null) return;
	
	var commentPosts = getElementChatPost(commentDiv,doc);
	var chatPost = commentPosts[0];
	var commentTexts = getElementCommentText(chatPost,doc);

	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){
		swakAddException(x);
	}
	var jellyfishstrings = document.getElementById("swaksmack-strings");
	var tooltip = '';
	var previewlink = doc.createElement("a");
	previewlink.className = 'swaksmacktinyurlpreview';
	turl = turl.replace(/tinyurl\.com/,"preview.tinyurl.com");
	previewlink.href = turl;
	if (useImage) {
		previewlink.innerHTML="<img src=\"chrome://swaksmack/skin/icons/monitor_link.png\"/>";
	}
	else {
		previewlink.textContent = '(preview)';
	}
	tooltip = jellyfishstrings.getString("tinyurl_preview_tooltip");
	previewlink.title = tooltip;
	previewlink.rel="external";

	element.parentNode.parentNode.insertBefore(previewlink, element.parentNode.nextSibling);
	var space = doc.createTextNode(' ');
	element.parentNode.parentNode.insertBefore(space, previewlink);
}

function buildReply_ORG(username,replytext) {
	//alert('buildReply ' + username);
	if (username == null) return '';
	var prefix = SS_getPreference(SMACK_REPLYPREFIX);
	var suffix = SS_getPreference(SMACK_REPLYSUFFIX);
	var reply = prefix + username;
	if (replytext != null && replytext != '')
	reply = reply + " " + replytext + suffix + ' ';
	else
		reply = reply + suffix + ' ';
		return reply;

	}
	
	function buildReply(username,replytext) {
	//alert('buildReply ' + username);
	if (username == null) return '';
	//var prefix = SS_getPreference(SMACK_REPLYPREFIX);
	//var suffix = SS_getPreference(SMACK_REPLYSUFFIX);
	
	var prefix = SS_prefs.getComplexValue(SMACK_REPLYPREFIX,
      Components.interfaces.nsISupportsString).data;
  var suffix = SS_prefs.getComplexValue(SMACK_REPLYSUFFIX,
      Components.interfaces.nsISupportsString).data;   
      try {
      	var str = Components.classes["@mozilla.org/supports-string;1"]
      .createInstance(Components.interfaces.nsISupportsString);
      str.data = "@#$";
   //   SS_prefs.setComplexValue(SMACK_REPLYPREFIX, Components.interfaces.nsISupportsString, str);
    }
    catch (x) {alert(x);}
       
	var reply = prefix + username;
	if (replytext != null && replytext != '')
	reply = reply + " " + replytext + suffix + ' ';
	else
		reply = reply + suffix + ' ';
		return reply;

	}
	

	function highlightUsername(element, doc) {
		if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
			return;
		}
		var dynunoption = SS_getPreference(SMACK_HL_DYNUNOPT);
		//alert('highlightUsername dynunoption ' + dynunoption);
		var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
		var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
		var commentPosts = getElementChatPost(element,doc);
		var chatPost = commentPosts[0];
		var textColor = SS_getPreference(SMACK_TCHL1);
		var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
		var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
		var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
		var hlopt = "1";
		if (dynunoption == "2"){
			hlopt = "2";
			highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL2);
			outlinePost = SS_getPreference(SMACK_OUTLINEHL2);
			textColor = SS_getPreference(SMACK_TCHL2);
			bkgrdColor = SS_getPreference(SMACK_BTCHL2);
			outlinePost = SS_getPreference(SMACK_OUTLINEHL2);
			highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL2);
		}
		else if (dynunoption == "3") {
			hlopt = "3";
			highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL3);
			outlinePost = SS_getPreference(SMACK_OUTLINEHL3);
			textColor = SS_getPreference(SMACK_TCHL3);
			bkgrdColor = SS_getPreference(SMACK_BTCHL3);
			outlinePost = SS_getPreference(SMACK_OUTLINEHL3);
			highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL3);
		}
		
		var chatNick = getElementChatNick(chatPost,doc);

		if (highlightUsernameOnly) {
			//just highlight username
			highlightBackgroundAndText(chatNick[0],bkgrdColor,textColor);

		}
		else if (!outlinePost) {
			highlightBackgroundAndText(chatPost,bkgrdColor,textColor);
		}

		if (outlinePost == true) {
			highlightOutline(chatPost,bkgrdColor);
		}

		element.setAttribute('swaksmackusernamehighlighted',true);
		element.setAttribute('swaksmackhlcss',hlopt);
		if (swaksmack.smackCommentsHidden == true) {
			hideChatComment(element, false);
		}
	}

	function unhighlightUsername(element, doc) {
		if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
			return;
		}
		//alert('unhighlight');
		var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
		var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
		var commentPosts = getElementChatPost(element,doc);
		var chatPost = commentPosts[0];
		chatPost.style.border='none';
		chatPost.style.background = 'inherit';
		chatPost.style.color = 'inherit';

		var chatNick = getElementChatNick(chatPost,doc);

		highlightBackgroundAndText(chatNick[0],null,null);

		element.setAttribute('swaksmackusernamehighlighted',false);
		element.setAttribute('swaksmackhlcss','');
		if (swaksmack.smackCommentsHidden == true) {
			hideChatComment(element, true);
		}
	}
	
	function buildUsernameRegex(usernames,chatwildcardmatch,dynamicUNArray) {
		if ((usernames == null || usernames.length ==0) && (dynamicUNArray == null || dynamicUNArray.length == 0)) return null;
		var temp = usernames.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(',');
		temp = buildSearchString(temp, chatwildcardmatch);
		if (dynamicUNArray != null && dynamicUNArray.length >0) {
			var dwords = buildSearchString(dynamicUNArray, chatwildcardmatch);
			temp = temp + '|' + dwords;
		}
		
		
		temp = temp.replace(/(\|$)|(,$)/g,'');
		temp = '(' + temp + ')';
		var re = null;
		re = new RegExp(temp,"ig");  //was ig
		return re;
	}
	
		function buildIgnoredUsernameRegex(usernames,chatwildcardmatch,dynamicUNArray) {
		if ((usernames == null || usernames.length ==0) && (dynamicUNArray == null || dynamicUNArray.length == 0)) return null;
		var temp = usernames.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(',');
		temp = buildSearchString(temp, chatwildcardmatch);
		if (dynamicUNArray != null && dynamicUNArray.length >0) {
			var dwords = buildSearchString(dynamicUNArray, chatwildcardmatch);
			temp = temp + '|' + dwords;
		}
		
		
		temp = temp.replace(/(\|$)|(,$)/g,'');
		temp = '[A-z0-9_+=-~!:;.%*$#@^<>{}?\\[\\]]*(' + temp + ')[A-z0-9_+=-~!:;.%*$#@^<>{}?\\[\\]]*';
		var re = null;
		re = new RegExp(temp,"ig");  //was ig
		return re;
	}
	
	function buildKeywordRegex(keywords,chatwildcardmatch,ignoreCase,dynamicKWArray) {
		if ((keywords == null || keywords.length ==0) && (dynamicKWArray == null || dynamicKWArray.length == 0)) return null;
		var temp = keywords.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(',');
		temp = buildSearchString(temp, chatwildcardmatch);
		if (dynamicKWArray != null && dynamicKWArray.length >0) {
			var dwords = buildSearchString(dynamicKWArray, true);  // chatwildcardmatch
			temp = temp + '|' + dwords;
		}
		
		
		temp = temp.replace(/(\|$)|(,$)/g,'');
		temp = '(' + temp + ')';
		var re = null;
		if(ignoreCase == true) re = new RegExp(temp,"ig");  //was ig
		else re = new RegExp(temp,"g"); //was "g"
		return re;
	}
	
	function buildIgnoreKeywordRegex(ignoredKeywords,ignoreCase) {
		if (ignoredKeywords == null || ignoredKeywords.length == 0) return null;
		var temp = ignoredKeywords.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(',');
		temp = buildSearchString(temp, true);
		temp = temp.replace(/(\|$)|(,$)/g,'');
		temp = '[A-z0-9_+=-~!:;%.*$#@^<>{}?\\[\\]]*(' + temp + ')[A-z0-9_+=-~!:;%.*$#@^<>{}?\\[\\]]*';
		var re = null;
		if(ignoreCase == true) re = new RegExp(temp,"ig");
		else re = new RegExp(temp,"g");
		return re;
	}
	
	function updateChatHighlighting(doc) {
		//alert('updateChatHighlighting');
		var keywords = SS_getPreference(SMACK_KEYWORDHL1);
		var usernames =SS_getPreference(SMACK_USERNAMEHL1);
		var chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD1);
		var ignoreCase = SS_getPreference(SMACK_IGNORECASEHL);
		var dynunoption = SS_getPreference(SMACK_HL_DYNUNOPT);
		var dynkwoption = SS_getPreference(SMACK_HL_DYNKWOPT);

		if(JF_keywordArray == null || JF_keywordArray.length == 0) {
			if(dynkwoption == "1") {
				JF_keywordArray[0] = buildKeywordRegex(keywords,chatwildcardmatch,ignoreCase,SS_dynamicKeywords);
				
			}
			else {
				JF_keywordArray[0] = buildKeywordRegex(keywords,chatwildcardmatch,ignoreCase,null);
			}
			var kwhlignore = SS_getPreference(SMACK_KEYWORDIGNOREHL1);
			JF_keywordHLIgnoreArray[0] = buildIgnoreKeywordRegex(kwhlignore,ignoreCase);
			
			
			var bccss = SS_getPreference(SMACK_BTCHL1);
			var tccss = SS_getPreference(SMACK_TCHL1);
			var swackcss = "swakhl1css";
			insertPostInfoCSS(doc,"1",swackcss,tccss,bccss);
			
			chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD2);
			var khl2 = SS_getPreference(SMACK_KEYWORDHL2);
			if(dynkwoption == "2") {
				JF_keywordArray[1] = buildKeywordRegex(khl2,chatwildcardmatch,ignoreCase,SS_dynamicKeywords);
			}
			else {
				JF_keywordArray[1] = buildKeywordRegex(khl2,chatwildcardmatch,ignoreCase,null);
			}
			kwhlignore = SS_getPreference(SMACK_KEYWORDIGNOREHL2);
			JF_keywordHLIgnoreArray[1] = buildIgnoreKeywordRegex(kwhlignore,ignoreCase);
			bccss = SS_getPreference(SMACK_BTCHL2);
			tccss = SS_getPreference(SMACK_TCHL2);
			swackcss = "swakhl2css";
			insertPostInfoCSS(doc,"2",swackcss,tccss,bccss);
			
			
			chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD3);
			var khl3 = SS_getPreference(SMACK_KEYWORDHL3);
			if(dynkwoption == "3") {
				JF_keywordArray[2] = buildKeywordRegex(khl3,chatwildcardmatch,ignoreCase,SS_dynamicKeywords);
			}
			else {
				JF_keywordArray[2] = buildKeywordRegex(khl3,chatwildcardmatch,ignoreCase,null);
			}
			kwhlignore = SS_getPreference(SMACK_KEYWORDIGNOREHL3);
			JF_keywordHLIgnoreArray[2] = buildIgnoreKeywordRegex(kwhlignore,ignoreCase);
			bccss = SS_getPreference(SMACK_BTCHL3);
			tccss = SS_getPreference(SMACK_TCHL3);
			swackcss = "swakhl3css";
			insertPostInfoCSS(doc,"3",swackcss,tccss,bccss);
			
		}

		if (JF_usernameArray == null || JF_usernameArray.length == 0) {
			
			//alert('JF_usernameArray length is 0');
			chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD1);
			if(dynunoption == "1") {
				JF_usernameArray[0] = buildUsernameRegex(usernames,chatwildcardmatch,SS_dynamicUsernames);
			}
			else {
				JF_usernameArray[0] = buildUsernameRegex(usernames,chatwildcardmatch,null);
			}
			var unhlignore = SS_getPreference(SMACK_USERNAMEIGNOREHL1);
			JF_usernameHLIgnoreArray[0] = buildIgnoredUsernameRegex(unhlignore,true,null);
			
			var uhl2 = SS_getPreference(SMACK_USERNAMEHL2);	
			chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD2);
			if(dynunoption == "2") {
				JF_usernameArray[1] = buildUsernameRegex(uhl2,chatwildcardmatch,SS_dynamicUsernames);
			}
			else {
				JF_usernameArray[1] = buildUsernameRegex(uhl2,chatwildcardmatch,null);
			}
			unhlignore = SS_getPreference(SMACK_USERNAMEIGNOREHL2);
			JF_usernameHLIgnoreArray[1] = buildIgnoredUsernameRegex(unhlignore,true,null);
			
			var uhl3 = SS_getPreference(SMACK_USERNAMEHL3);	
			chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD3);
			if(dynunoption == "3") {
				JF_usernameArray[2] = buildUsernameRegex(uhl3,chatwildcardmatch,SS_dynamicUsernames);
			}
			else {
				JF_usernameArray[2] = buildUsernameRegex(uhl3,chatwildcardmatch,null);
			}
			unhlignore = SS_getPreference(SMACK_USERNAMEIGNOREHL3);
			JF_usernameHLIgnoreArray[2] = buildIgnoredUsernameRegex(unhlignore,true,null);
			
		}
	}

	function commentColor(element, doc) {
		if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
			return;
		}

		element.setAttribute('swaksmackusernamehighlighted',false);
		element.setAttribute('swaksmackkeywordhighlighted',false);

		
		var ignorePostsEnabled= SS_getPreference(SMACK_ENABLEIGNORE1);
		

	
		var ignoreSelfPosts = SS_getPreference(SMACK_IGNORESPHL);
		var hideAvatar = SS_getPreference(SMACK_ENHANCEHIDEAVATARS);
		var highlightJFEmployees = SS_getPreference(SMACK_HL_ENABLEJFEMPLOYEE);

		var userMuted = false;
		var employeeMatch = null;

		var commentPosts = getElementChatPost(element,doc);
		var chatPost = commentPosts[0];
		if (chatPost == null)  {
			//user may be muted
			commentPosts = getElementsByClassName("chatPostMuted",element,doc);
			chatPost = commentPosts[0];
			if (chatPost != null) {
				//alert('chat post muted detected');
				userMuted = true;
			}
			else {
				//chat post not found at all
				return;
			}
		}
		

		var commentTexts = getElementCommentText(chatPost,doc);
		var chatNick = getElementChatNick(chatPost,doc);
		if (commentTexts == null || chatNick == null) return;

		if (hideAvatar) {
			var chatAvatar = getElementChatAvatar(chatPost,doc);
			chatAvatar[0].style.display='none';
		}


		if (ignoreSelfPosts) {
			var nickname = swaksmack.SS_JF.getNickName();
			if (chatNick[0].textContent == nickname) return;
		}

		if (ignorePostsEnabled) {
			
	//		var ignorelist2 = SS_getPreference(SMACK_IGNORELIST2);
	//		var ignorelistattend = SS_getPreference(SMACK_IGNORELISTATTEND);
			
			
			if (JF_ignoreUserlistRegExp == null) {
				var ignorelist =SS_getPreference(SMACK_IGNORELIST1);		
				if (ignorelist != null && ignorelist != "") {
					var blockwildcardmatch = SS_getPreference(SMACK_BLOCKWILDCARD);
					ignorelist = ignorelist.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
					ignorelist = buildSearchString(ignorelist,blockwildcardmatch);
					//ending with a | or , can be bad
					ignorelist = ignorelist.replace(/(\|$)|(,$)/,'');

					JF_ignoreUserlistRegExp = new RegExp(ignorelist,"ig");
				}
			}
			
			
			//check post against ignore list
	

				//alert(usernames);
				if (JF_ignoreUserlistRegExp != null) {
					JF_ignoreUserlistRegExp.lastIndex = 0;
					var ignoreListMatch = isUsernameMatch(chatNick[0],JF_ignoreUserlistRegExp);
					if (ignoreListMatch) {
						var funMode= SS_getPreference(SMACK_FUNIGNORE1);
						if (funMode == true && userMuted == false) {
							commentTexts[0].textContent = swaksmack.smackFunController.getFunComment();
							if (SS_getPreference(SMACK_ENABLE_FUNAVATAR) == true) {
								var chatAvatar = getElementChatAvatar(chatPost,doc);
								chatAvatar[0].setAttribute('src','chrome://swaksmack/skin/images/swakavatarfun1.jpg');
								if (SS_getPreference(SMACK_DISPLAYLARGEAVATAR) ==true) {
									chatAvatar[0].setAttribute('src','chrome://swaksmack/skin/images/swakavatarfun1large.jpg');
									var chatAvatarCont = getElementChatAvatarContainer(chatPost,doc);
									var size = SS_getPreference(SMACK_DISPLAYAVATARSIZE);
	
									chatAvatarCont[0].style.width = size + 'px';  //'75px';  //75px
									chatAvatarCont[0].style.height = size + 'px';//'75px';
									if (size ==75) {
										size = 'auto';
									}
									else {
										size = size +'px';
									}
									if (chatAvatar[0].width > chatAvatar[0].height) {
				
										chatAvatar[0].setAttribute('width', size);
										chatAvatar[0].setAttribute('height', 'auto');
									}
									else {
										chatAvatar[0].setAttribute('width', 'auto');
										chatAvatar[0].setAttribute('height', size);
									}
									chatAvatar[0].style.maxWidth = size; //'100px';
									chatAvatar[0].style.maxHeight = size;  //'100px';
									if (size == 'auto') {
										chatAvatar[0].style.maxWidth = '75px';
										chatAvatar[0].style.maxHeight = '75px'; 
									}	
									
								}
							}
						}
						else {
							element.style.display='none';
						}
						return;
					}
				}
	//		}

			if (JF_ignoreWordlistRegExp == null) {
				var ignorelist2 = SS_getPreference(SMACK_IGNORELIST2);
				
				if (ignorelist2 != null && ignorelist2 != "") {
					var blockwildcardmatch = SS_getPreference(SMACK_BLOCKWILDCARD);
					
					ignorelist2 = ignorelist2.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
					//alert('ignorelist2 ' + ignorelist2);
					ignorelist2 = buildSearchString(ignorelist2,blockwildcardmatch);
					//ending with a | or , can be bad
					ignorelist2 = ignorelist2.replace(/(\|$)|(,$)/,'');
					//alert(usernames);
					JF_ignoreWordlistRegExp = new RegExp(ignorelist2,"ig");
					//alert('JF_ignoreWordlistRegExp '+ JF_ignoreWordlistRegExp);
				}
			}
			
			if (JF_ignoreWordlistRegExp != null) {
					var it = commentTexts[0].textContent;
					JF_ignoreWordlistRegExp.lastIndex = 0;
				//	alert('ignore text ' + it);
					var ignoreListMatch = JF_ignoreWordlistRegExp.test(it);
					
					if (ignoreListMatch) {
						//alert('ignoring post based on keyword');
						element.style.display='none';
						return;
					}
					
					
				}

			
			if (JF_ignoreAttendancelistRegExp == null) {
				var ignorelistattend = SS_getPreference(SMACK_IGNORELISTATTEND);
				if (ignorelistattend != null && ignorelistattend != "") {
					ignorelistattend = ignorelistattend.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
					ignorelistattend = buildSearchString(ignorelistattend, false);
					//ending with a | or , can be bad
					ignorelistattend = ignorelistattend.replace(/(\|$)|(,$)/,'');
					//allow for leading and trailing white space
					ignorelistattend = "^\\s*(" +ignorelistattend +")\\s*$";
					JF_ignoreAttendancelistRegExp = new RegExp(ignorelistattend,"ig");
				}
			}
			
			if ( JF_ignoreAttendancelistRegExp != null) {
					JF_ignoreAttendancelistRegExp.lastIndex = 0;
					//alert('ignorelistRegExp ' + ignorelistRegExp);
					var it = commentTexts[0].textContent;
					var ignoreListMatch = JF_ignoreAttendancelistRegExp.test(it);
					if (ignoreListMatch) {
						//alert('ignoring attendance post ' + it);
						element.style.display='none';
						return;
					}
				}
			
			
			try{
				var noobIgnore = SS_getPreference(SMACK_ENABLE_NOOBIGNORE);
				if (noobIgnore) {
					var noobThreshold = SS_getPreference(SMACK_NOOBIGNORE_THRESHOLD);
					var chatGuru = getElementChatGuru(chatPost,doc);
					if (chatGuru != null && chatGuru[0] != null){
						var gp = chatGuru[0].textContent.replace(/[()]*/g,'');
						gp = parseInt(gp);
						if (gp <= noobThreshold) {
							employeeMatch = isJFEmployee(element,doc);
							var admin = getElementsByClassName('administrator',element,doc);
							if (employeeMatch == false && (admin[0]==null)) {
								element.style.display='none';
								return;
							}
						}
					}
				}
		}
		catch(x) {
			swakAddException(x);	
		}			
		} //end ignore enabled
		//what's the conop for muted posts?  For now just ignore them is applicable 
		if (userMuted == true) {
			return;
		}
		
		var ignoreAvatarMatch = SS_getPreference(SMACK_IGNOREALLAVATARS);
		
			if (ignoreAvatarMatch == false && JF_ignoreAvatarlistRegExp == null) {
				var ignoreavatar = SS_getPreference(SMACK_IGNOREAVATARLIST);
				if (ignoreavatar != null && ignoreavatar != "") {
					ignoreavatar = ignoreavatar.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
					ignoreavatar = buildSearchString(ignoreavatar, false);
					//ending with a | or , can be bad
					ignoreavatar = ignoreavatar.replace(/(\|$)|(,$)/,'');
					//allow for leading and trailing white space
					ignoreavatar = "^\\s*(" +ignoreavatar +")\\s*$";
					JF_ignoreAvatarlistRegExp = new RegExp(ignoreavatar,"ig");
				}
			}
			
			
			
			if (ignoreAvatarMatch == true) {
				var replacementAvatar = SS_getPreference(SMACK_IGNOREAVATARPIC);
				if (replacementAvatar != null && replacementAvatar != '') {
					var chatAvatar = getElementChatAvatar(chatPost,doc);
					chatAvatar[0].setAttribute('src',replacementAvatar);
					chatAvatar[0].setAttribute('onerror','this.src=\'chrome://swaksmack/skin/error1.png\'');
				}
			}
			else if(JF_ignoreAvatarlistRegExp != null) {
				JF_ignoreAvatarlistRegExp.lastIndex = 0;
				ignoreAvatarMatch = isUsernameMatch(chatNick[0],JF_ignoreAvatarlistRegExp);
				if (ignoreAvatarMatch) {
					var replacementAvatar = SS_getPreference(SMACK_IGNOREAVATARPIC);
					if (replacementAvatar != null && replacementAvatar != '') {
						var chatAvatar = getElementChatAvatar(chatPost,doc);
						//alert('replacement avatar ' + replacementAvatar);
						chatAvatar[0].setAttribute('src',replacementAvatar);
						chatAvatar[0].setAttribute('onerror','this.src=\'chrome://swaksmack/skin/error1.png\'');
					}
				}				
			}
		
		
		var filterAllCaps = SS_getPreference(SMACK_ENABLECAPSUPRESSION);
		if (filterAllCaps == true) {
			var newtext = swakReplaceAllCaps(commentTexts[0].textContent);
			if (newtext != null) {
				//alert('All CAPS replaced for ' + commentTexts[0].textContent);
				commentTexts[0].textContent = newtext;
			}
		}
		
		updateChatHighlighting(doc);
		
		if (highlightJFEmployees && employeeMatch == null) {
			employeeMatch = isJFEmployee(element,doc);
		}
		
		var displayLargeAvatar = SS_getPreference(SMACK_DISPLAYLARGEAVATAR);
		if (displayLargeAvatar == true) {
			var size = SS_getPreference(SMACK_DISPLAYAVATARSIZE);
			var chatAvatar = getElementChatAvatar(chatPost,doc);
			var chatAvatarCont = getElementChatAvatarContainer(chatPost,doc);
			var cs = chatAvatar[0].getAttribute('src');
			//cs = cs.replace(/_m[.]jpg/,'.jpg');
			cs = cs.replace(/_m[.](jpg|png|gif)/g, ".$1");
			//alert('large av cs ' + cs);
			chatAvatar[0].setAttribute('src',cs);
			//alert('chatAvatar[0] img width ' + chatAvatar[0].width);
	//		chatAvatarCont[0].style.maxWidth = size +'px'; //'100px';
	//		chatAvatarCont[0].style.maxHeight = size + 'px';  //'100px';			
			chatAvatarCont[0].style.width = size +'px'; //'100px';
			chatAvatarCont[0].style.height = size + 'px';  //'100px';
			if (size ==75) {
				size = 'auto';
			}
			else {
				size = size +'px';
			}
			if (chatAvatar[0].width > chatAvatar[0].height) {
		
				chatAvatar[0].setAttribute('width', size);
				chatAvatar[0].setAttribute('height', 'auto');
		
				
			}
			else {
				chatAvatar[0].setAttribute('width', 'auto');
				chatAvatar[0].setAttribute('height', size);

			}
			
			chatAvatar[0].style.maxWidth = size; //'100px';
			chatAvatar[0].style.maxHeight = size;  //'100px';
			if (size == 'auto') {
				chatAvatar[0].style.maxWidth = '75px';
				chatAvatar[0].style.maxHeight = '75px'; 
			}	
			
			
		
		/*
//large	
	//		var cs = chatAvatar[0].getAttribute('src');
	//		cs = cs.replace(/_m/,'');
	//		chatAvatar[0].setAttribute('src',cs);
			
			//var chatAvatarCont = getElementsByClassName('chatAvatarContainer',chatPost);  //"chatNick" "chatAvatarContainer"
			chatAvatarCont[0].style.width = '75px';
			chatAvatarCont[0].style.height = '75px';
			*/
		}
		
		var chatRegExp = null;


				searchFound = false;

				var keywordMatch = false;
				var userNameMatch = false;
				var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
				var highlightKeywordsOnly = SS_getPreference(SMACK_WORDONLYHL1);
				var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
				var underlineMatch = SS_getPreference(SMACK_UNDERLINEHL1);
				var jfemployeeopt = parseInt(SS_getPreference(SMACK_HL_JFEMPLOYEEOPT));
				jfemployeeopt = jfemployeeopt-1;
				var hlMatchFound = false;
				var hlenabled = true;
				
				for (var i=0;i<3;i++) {
					if (JF_keywordArray[i] == null && JF_usernameArray[i] == null && highlightJFEmployees == false) continue;
					
					var bkgrdColor = null;
					var textColor = null;
					if (i == 0) {
						hlenabled = SS_getPreference(SMACK_ENABLEHL1);
						if (hlenabled == false) continue;
						bkgrdColor = SS_getPreference(SMACK_BTCHL1);
						textColor = SS_getPreference(SMACK_TCHL1);
						outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
						highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
						underlineMatch = SS_getPreference(SMACK_UNDERLINEHL1);
						highlightKeywordsOnly = SS_getPreference(SMACK_WORDONLYHL1);
					}
					else if (i == 1) {
						hlenabled = SS_getPreference(SMACK_ENABLEHL2);
						if (hlenabled == false) continue;
						bkgrdColor = SS_getPreference(SMACK_BTCHL2);
						textColor = SS_getPreference(SMACK_TCHL2);
						outlinePost = SS_getPreference(SMACK_OUTLINEHL2);
						highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL2);
						underlineMatch = SS_getPreference(SMACK_UNDERLINEHL2);
						highlightKeywordsOnly = SS_getPreference(SMACK_WORDONLYHL2);
					}
					else if (i == 2) {
						hlenabled = SS_getPreference(SMACK_ENABLEHL3);
						if (hlenabled == false) continue;
						bkgrdColor = SS_getPreference(SMACK_BTCHL3);
						textColor = SS_getPreference(SMACK_TCHL3);
						outlinePost = SS_getPreference(SMACK_OUTLINEHL3);
						highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL3);
						underlineMatch = SS_getPreference(SMACK_UNDERLINEHL3);
						highlightKeywordsOnly = SS_getPreference(SMACK_WORDONLYHL3);
					}
				
				
				if (JF_keywordArray[i] != null) {
					JF_keywordArray[i].lastIndex = 0;
					keywordMatch = colorByComment(commentTexts[0],JF_keywordArray[i],JF_keywordHLIgnoreArray[i],highlightKeywordsOnly,underlineMatch,textColor,bkgrdColor);
				//ad a tag to indicate that post has been highlighted
				if (keywordMatch == true) {
					hlMatchFound = true;
					var hlopt = i+1;
					element.setAttribute('swaksmackkeywordhighlighted',true);
					element.setAttribute('swaksmackhlcss',hlopt);
					
					var soundFile = SS_getPreference(SMACK_AUDIOSOUND_CHATKEYWORD);
					swaksmack.audioManager.playAudioAlert(soundFile);
				}
				
				if (keywordMatch == true && highlightKeywordsOnly == false && !outlinePost) {
					highlightBackgroundAndText(chatPost,bkgrdColor,textColor);
					break;
				}
				if (keywordMatch == true && outlinePost) {
						highlightOutline(chatPost,bkgrdColor);
						break;
				}
				
			}//null check
					
			if (JF_usernameArray[i] != null) {
				JF_usernameArray[i].lastIndex = 0;
				userNameMatch = colorByUsername(chatNick[0],JF_usernameArray[i],JF_usernameHLIgnoreArray[i]); //
				
				if (userNameMatch) {
					hlMatchFound = true;
					element.setAttribute('swaksmackusernamehighlighted',true);
					var hlopt = i+1;
					element.setAttribute('swaksmackhlcss',hlopt);
					if (highlightUsernameOnly) {
						//just highlight username	
						highlightBackgroundAndText(chatNick[0],bkgrdColor,textColor);
					}
					else if (!outlinePost) {	
						highlightBackgroundAndText(chatPost,bkgrdColor,textColor);
					}
					if (outlinePost) {

						highlightOutline(chatPost,bkgrdColor);
					}
					
					var soundFile = SS_getPreference(SMACK_AUDIOSOUND_CHATUSERNAME);
					swaksmack.audioManager.playAudioAlert(soundFile);
					//match found break
					break;
				}		
			}


	

			if (hlMatchFound == false && highlightJFEmployees == true && i == jfemployeeopt) {
				if (employeeMatch == true) {
					//alert('JF employee found');
					var hlopt = i+1;
					element.setAttribute('swaksmackusernamehighlighted',true);
					element.setAttribute('swaksmackhlcss',hlopt);
					if (highlightUsernameOnly) {
						//just highlight username		
						highlightBackgroundAndText(chatNick[0],bkgrdColor,textColor);
					}
					else if (!outlinePost) {

						highlightBackgroundAndText(chatPost,bkgrdColor,textColor);
					}
					if (outlinePost) {		
						highlightOutline(chatPost,bkgrdColor);
					}
					//match found break
					break;
				}
			}
	
				
			}//end for
			
				if (swaksmack.smackCommentsHidden == true && hlMatchFound == false) {
					hideChatComment(element, true);
				}
				else {
					hideChatComment(element, false);
				}
			
			  if (hlMatchFound == true) {
			  	updateStatusbarKeyword(5);
			  }
			}
			
			function insertPostInfoCSS(doc,hlopt,cssid,textColor,bkColor) {
				if (doc == null) return;
				var heads = doc.getElementsByTagName("head");
				if (heads.length > 0) {
						var swakcss = doc.getElementById(cssid);
						if (swakcss != null) {
							heads[0].removeChild(swakcss);
						}
						if ((hlopt == "1" && SS_getPreference(SMACK_CHATINFOHL1) == true) ||
							(hlopt == "2" && SS_getPreference(SMACK_CHATINFOHL2) == true) ||
							(hlopt == "3" && SS_getPreference(SMACK_CHATINFOHL3) == true)) {
				
							var node = doc.createElement("style");
							node.id=cssid;
							
    					var chatcss = buildPostInfoCSS(hlopt,textColor,bkColor);
							//var chatcss = buildPostInfoCSS(hlopt,bkColor,textColor);
							node.innerHTML = chatcss;
							node.type = "text/css";
							heads[0].appendChild(node);
							//alert('swakcss added for ' + cssid);
						}

					}
			}
			
			function buildPostInfoCSS(hlopt,textColor,bkColor) {
				//var css = "#chat > [swaksmackhlcss=\"" + hlopt+"\"] a.chatNick, #chat > [swaksmackhlcss=\"" + hlopt+"\"] span.chatTime, #chat > [swaksmackhlcss=\"" + hlopt+"\"] span.chatGuru, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.chatMute, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackReply, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackUnhighlightUser, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackHighlightUser{color: " + textColor + "; background: " + bkColor+ "; font-size: 11px;}";
				var css = "#chat > [swaksmackhlcss=\"" + hlopt+"\"] a.chatNick, #chat > [swaksmackhlcss=\"" + hlopt+"\"] span.chatTime, #chat > [swaksmackhlcss=\"" + hlopt+"\"] span.chatGuru, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.chatMute, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackReply, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackUnhighlightUser, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackHighlightUser, #chat > [swaksmackhlcss=\"" + hlopt+"\"] a.swaksmackAction {color: " + textColor + " ! important; font-size: 11px;}";
				return css;
			}
			
			function updateChatThemeCSS(doc) {
				if (doc == null) return;
				var heads = doc.getElementsByTagName("head");
				var enabled = SS_getPreference(SMACK_THEME_ENABLE);
				if (heads.length > 0) {
					
					var swakthemecss = doc.getElementById('swakchattheme');
					if (swakthemecss != null) {
						heads[0].removeChild(swakthemecss);
					}
					if (enabled == false) {	
						return;
					}
					
					var textColor = SS_getPreference(SMACK_THEME_CHATTC);
					var bkColor = SS_getPreference(SMACK_THEME_CHATBTC);
					var chatNick = SS_getPreference(SMACK_THEME_CHATNICK);
					var chatTime = SS_getPreference(SMACK_THEME_CHATTIME); 
					var chatGuru = SS_getPreference(SMACK_THEME_CHATGURU); 
					var chatActions = SS_getPreference(SMACK_THEME_CHATACTIONS);
					var chatLinks = SS_getPreference(SMACK_THEME_CHATLINKS);
					var cBkgrd = SS_getPreference(SMACK_THEME_BKGRD);
					
					var node = doc.createElement("style");
					node.id='swakchattheme';
					
					var css = "#rightPanel, #leftPanel, #chat, #chatContainer { background: " + cBkgrd + ";} #chat div.chatPost:not(.moderator) a.chatNick { color: " + chatNick + ";} #chat .commentFloatContainer {color: " + textColor + "; background: " + bkColor+ ";} #chat div.chatPost:not(.moderator) {color: " + textColor + ";} #chat div.chatPost:not(.moderator) a.chatMute, #chat div.chatPost:not(.moderator) a.swaksmackHighlightUser, #chat div.chatPost:not(.moderator) a.swaksmackUnhighlightUser, div.chatPost:not(.moderator) a.swaksmackReply, #chat div.chatPost:not(.moderator) a.swaksmackAction { color: " + chatActions + ";} #chat div.chatPost:not(.moderator) span.chatTime { color: " + chatTime + ";} #chat div.chatPost:not(.moderator) span.chatGuru { color: " + chatGuru + ";} #chat div.commentText a:visited, #chat div.commentText a:link { color: " + chatLinks + ";} #chat div.administrator, #chat div.administrator a.swaksmackReply, #chat div.administrator a.swaksmackHighlightUser, #chat div.administrator a.swaksmackUnhighlightUser, #chat div.administrator a.swaksmackAction {color: " + "#FFFFFF ! important" + ";} #chat .administrator a.chatNick {color: " + "#021931 ! important" + ";} #chat .administrator .chatTime {color: " + "#7AFFCF ! important" + ";}";

					node.innerHTML = css;
					node.type = "text/css";
					heads[0].appendChild(node);
				}
			}

			function highlightOutline(element,bColor) {
				element.style.border='3px solid ' + bColor;
			}

			function highlightBackgroundAndText(element,bColor,fColor) {
				element.style.background = bColor;
				element.style.color = fColor;
			}

			function updateStatusbarKeyword(c) {
				if (swaksmack.SS_SBM == null) {
					return;
				}
				swaksmack.SS_SBM.flashKeywordButton(c);
			}

			function colorByComment(element, oRegExp, kwigRegExp, highlightKeywords, underlineMatch,textColor,bkgrdColor) {
				if (element == null || oRegExp == null) return false;
				if (highlightKeywords == null) highlightKeywords = false;
				//var underlineMatch = SS_getPreference(SMACK_UNDERLINEHL1);
				var matches;
				var inputText = element.textContent;
				
				//ignore word test
				if (kwigRegExp != null) {
					inputText = inputText.replace(kwigRegExp," ");
				}
				//var ire = new RegExp("remind|nevermind","ig");
				//inputText = inputText.replace(ire,' ');
				//
				
				var matchFound = false;

				//fix href links and so that we don't try to color/underline--will break link
				var badToColor = element.getElementsByTagName("a");

				//alert('regex ' + oRegExp);
				while ((matches = oRegExp.exec(inputText)) != null) {
				//	alert(kwigRegExp + ' input ' + inputText );
					matchFound = true;
					if (underlineMatch == false && highlightKeywords == false) break;
					//for now don't attempt to color/underline as the innerhtml replace will destroy the hrefs
					if (badToColor != null && badToColor[0] !=null) break;


					var text = matches[0];

					var lastKWMatchIndex = SS_colorCommentMatchArray.indexOf(text);
					if (lastKWMatchIndex != -1) {
						continue;

					}

					SS_colorCommentMatchArray.push(text);
					var regextext = SS_escapeRegExLiterals(text);


					//create a group that will define $1 in the regex
					regextext = '(' +regextext + ')';

					//need to build a new regex for the matched text since multiple words in the text may match
					var mRegExp = new RegExp(regextext,"g");
					//alert(mRegExp + ' mRegExp');


					//tag the found keyword(s) by wrapping them in some char we hope we never seen in a chat post
					element.textContent = element.textContent.replace(mRegExp, JF_taggedMatches);

				}

				//now replace the tagged matched words for underlined/highlighted words
				if (matchFound && (underlineMatch || highlightKeywords)) {
					// <([^>]*)>

					var pass2replace = "$1";
					if (underlineMatch == true) {
						pass2replace = SS_ulreplacement;
					}

					if (highlightKeywords == true) {
						pass2replace = '<span style=\"color:' + textColor +';background:' + bkgrdColor + '\">' + pass2replace + '</span>';
					}

					//replace all the tagged words in one replace of the innerhtml
					element.innerHTML = element.innerHTML.replace(JF_HL_repRegEx, pass2replace);

				}

				SS_colorCommentMatchArray = [];
				return matchFound;

			}

			function isUsernameMatch(element, oRegExp) {
				if (element == null || oRegExp == null) return false;
				var matchFound = false;
				var matches = oRegExp.exec(element.textContent);
				if (matches != null) {
					matchFound = true;
				}
				return matchFound;
			}

			function isJFEmployee(commentDiv, doc) {
				//employee badge info: <div class="largeBadge"><img alt="JF Employee" src="/img/ss/1184790884_employee.gif"/></div>
				var largeBadge = getElementLargeBadge(commentDiv,doc);
				//var largeBadge = getElementsByClassName("largeBadge",commentDiv);
				if (largeBadge == null || largeBadge[0] == null) return false;
				var imgs = largeBadge[0].getElementsByTagName("img");
				var found = false;
				for (var i=0;i<imgs.length;i++) {
					var alt = imgs[i].alt;
					if (alt == 'JF Employee') {
						found = true;
						break;
					}
				}
				return found;
			}

			function processSmackHero(commentDiv, doc) {
				if (commentDiv == null || doc == null) return;
				var largeBadge = getElementLargeBadge(commentDiv,doc);
				//var largeBadge = getElementsByClassName("largeBadge",commentDiv);
				if (largeBadge == null || largeBadge[0] == null) return;
				var imgs = largeBadge[0].getElementsByTagName("img");
				if (SS_getPreference(SMACK_DISPLAYHIDDENBADGES)) {
					largeBadge[0].style.display='block !override';
				}
				var shimg = null;
				for (var i=0;i<imgs.length;i++) {
					var alt = imgs[i].alt;
					if (alt == 'Smack Hero') {
						shimg = imgs[i];
						break;
					}
				}
				if (shimg == null) {
					return;
				}

				var link = doc.createElement("a");
				link.href = 'http://smackshopping.com';
				link.rel="external";
				var tooltip = '';
				var jellyfishstrings = document.getElementById("swaksmack-strings");
				tooltip = jellyfishstrings.getString("smackhero_link_tooltip");
				link.title=tooltip;
				shimg.parentNode.insertBefore(link, shimg);
				link.appendChild(shimg); // TEXT TO LINK

			}

			function colorByUsername(element, oRegExp, userIgnoreRegExp) {
				if (element == null || oRegExp == null) return false;
				var matchFound = false;
				var inputText = element.textContent;
				if (userIgnoreRegExp != null) {
					inputText = inputText.replace(userIgnoreRegExp," ");
				}
				
				var matches = oRegExp.exec(inputText); //was element.textContent
				if (matches != null) {
					matchFound = true;
					//alert(userIgnoreRegExp + ' inputText ' + inputText);
				}
				return matchFound;
			}

			function executePMLink(commentDiv, doc) {
				if (doc == null) doc = content.document;
				var chatDiv = doc.getElementById(commentDiv);
				var elements = doc.evaluate(".//text()", chatDiv, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
				if (elements == null) return;
				for (var i = 0; i < elements.snapshotLength; i++) textToLink(elements.snapshotItem(i), doc);
			}

			function execute(commentDiv, bool_highlight, doc)
			{
				//alert('execute ' +commentDiv.className);
				if (doc == null) return;
				if (commentDiv == null) return;
				if (commentDiv.id == null || commentDiv == 'undefined') return;
				if (bool_highlight == null) bool_highlight = true;
				
				JF_HTMLBadPost_RegExp.lastIndex = 0;
				JF_HTMLTag_regExp.lastIndex = 0;
				JF_BBCODETag_RegExp.lastIndex = 0;
				
				var commentTexts = null;
				var bbcoderemovetags = SS_getPreference(SMACK_DISPLAYBBCODEREMOVETAGS);
				var bbcodedisplay = SS_getPreference(SMACK_DISPLAYBBCODEPOSTS);
				var bbcode = bbcodedisplay || bbcoderemovetags;
				if (bbcode == true) {
					commentTexts = getElementCommentText(commentDiv,doc);
					bbcode = JF_BBCODETag_RegExp.test(commentTexts[0].textContent);
				}
				
				//remove bcodetags, then process post as 'normal'
				if (bbcodedisplay == false && (bbcoderemovetags && bbcode)) {
					processBBCode(commentTexts[0],true);
					bbcode = false;
				} 
				
				if (bbcode == false) {
					var elements = doc.evaluate(".//text()", commentDiv, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
					for (var ii = 0; ii < elements.snapshotLength; ii++) textToLink(elements.snapshotItem(ii), doc,commentDiv);
				}
				


				if (SS_getPreference(SMACK_ENHANCEDCHATUI) == true) {
					commentEnhance(commentDiv,doc);
					processSmackHero(commentDiv,doc);
				}

				if (bool_highlight == true && SS_getPreference(SMACK_GLOBAL_ENABLEHL) == true) {
					commentColor(commentDiv,doc);
				}
				
				if (isLRArea(doc) == true) {
					if (bbcode == true) {
						processBBCode(commentTexts[0],false);
						/*
						var cb = commentTexts[0].innerHTML;
						var threat = JF_HTMLBadPost_RegExp.test(cb);
						if (threat == false) {
							//alert('processing bbcode true');
							for(i = 0; i < bbsearch.length; i++) {
								
			     			commentTexts[0].innerHTML = commentTexts[0].innerHTML.replace(bbsearch[i],bbreplace[i]);
			     			
							}
						}
						*/
					}
			}
						
				externalLinks(commentDiv);


			}
			
	function processBBCode(innerhtmlOwner,removeTags) {
		if (innerhtmlOwner == null || innerhtmlOwner.innerHTML == '') return;
		if (removeTags == null) removeTags = false;
		if (removeTags == true) {
			for(i = 0; i < bbsearch.length; i++) {
					
	   		innerhtmlOwner.innerHTML = innerhtmlOwner.innerHTML.replace(bbsearch[i],bbtagremove[i]);
	   			
			}
		}
		else {
			var threat = JF_HTMLBadPost_RegExp.test(innerhtmlOwner.innerHTML);
			if (threat == false) {
				//alert('processing bbcode true');
				for(i = 0; i < bbsearch.length; i++) {
					
	   			innerhtmlOwner.innerHTML = innerhtmlOwner.innerHTML.replace(bbsearch[i],bbreplace[i]);
	   			
				}
			}
		}
	}

			function textToLink(element, doc, commentDiv)
			{
				if (element == null || element.nodeValue == null) return;
				//just perform the < replacement if HTML posts are disabled
		//		if (SS_getPreference(SMACK_DISPLAYCONVERTLT) && SS_getPreference(SMACK_DISPLAYHTMLPOSTS) == false) {
				if (SS_getPreference(SMACK_DISPLAYCONVERTLT)) {	
					element.nodeValue = element.nodeValue.replace(/&lt;|\u227a/gi,'<');
				}
				if (element.parentNode.tagName.match(SS_illegal)) return;
				var generousMatch = SS_getPreference(SMACK_EASYURL);
				var spamwarn = SS_getPreference(SMACK_URL_SPAMWARN);
				var matches = element.nodeValue.match(SS_uri);
				if (matches != null) {
					var text = matches[0];
					var index = element.nodeValue.indexOf(text);
					if (index == 0)
					{
						if (element.nodeValue.length > text.length) textToLink(element.splitText(text.length), doc, commentDiv);
						var link = doc.createElement("a");
						//TEST for fixing link ref that have puncuation on the end
						var newurl = element.nodeValue.replace(/([\.!,;:\*()]*)$/i,'');
						newurl = newurl.replace(/[a-z0-9]*\.{2,}/,'');
						link.href = newurl;

						//_TEST
						///073107 link.href = element.nodeValue;
						link.rel="external";
						element.parentNode.insertBefore(link, element);
						link.appendChild(element); // TEXT TO LINK
						if (spamwarn == true) {
							var spamcheck = swakSpamCheck(link.href);
							if (spamcheck == true) {
										//alert("Possible spam");
										element.nodeValue = element.nodeValue + " [SPAM?] ";
							}
						}
						if (SS_getPreference(SMACK_TINYURLPREVIEW) && tinyurlpreviewregex.test(newurl)) {
							var tufound = tinyurlpreviewregex.test(newurl);
							previewTinyURL(element, doc, newurl, commentDiv);
						}
						slimFastUrl(element,doc);
					}
					else textToLink(element.splitText(index), doc, commentDiv);
					}
					else if (generousMatch == true){
						matches = element.nodeValue.match(SS_uri2);
						if (matches != null) {
							var text = matches[0];
							var emailFound = false;
							if (text.indexOf("@") != -1) emailFound = true;
							var index = element.nodeValue.indexOf(text);
							if (index == 0)
							{
								if (element.nodeValue.length > text.length) textToLink(element.splitText(text.length), doc, commentDiv);
								var link = doc.createElement("a");
								var newurl = element.nodeValue.replace(/^([\.!,;:\*()]*)/i,'');
								newurl = newurl.replace(/[a-z0-9]*\.{2,}/,'');
								//link.href = 'http://'+element.nodeValue;
								link.href = 'http://'+ newurl;
								if (emailFound == true) {
									link.href = 'mailto:'+newurl;
								}
								link.rel="external";
								element.parentNode.insertBefore(link, element);
								link.appendChild(element); // TEXT TO LINK
								if (spamwarn == true) {
									var spamcheck = swakSpamCheck(link.href);
									if (spamcheck == true) {
										//alert("Possible spam");
										element.nodeValue = element.nodeValue + " [SPAM?] ";
									}
								}

								if (SS_getPreference(SMACK_TINYURLPREVIEW) && tinyurlpreviewregex.test(newurl)) {
									previewTinyURL(element, doc, link.href, commentDiv);
								}
								slimFastUrl(element,doc);
							}
							else textToLink(element.splitText(index), doc, commentDiv);
							}
						}

					}
					
					function swakSpamCheck(link) {
						if (link == null) return false;
						
						//var re = new RegExp("(http:\/\/)?(www[.])?([a-z0-9+-/.\(@\)?]*)","ig");
						//var re = new RegExp("(http:\/\/)?(www[.])?(internetisseriousbusiness.com|tinyurl.com/2nmscj)","ig");
						var f = SwakURLSpamWarnRegEx.test(link);

						return f;
					}

					function slimFastUrl(element,doc){
						if(element == null) return;
						if (doc == null) return;
						var trimUrlLength = SS_getPreference(SMACK_MAXURL);
						if (trimUrlLength == false) return;
						var maxUrlLength = SS_getPreference(SMACK_MAXLENGTH);
						if (maxUrlLength <=0) {
							var jellyfishstrings = document.getElementById("swaksmack-strings");
							var error = jellyfishstrings.getString("maxUrlLengthError1");
							alert(error);
							//var defPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService.getDefaultBranch());
							var defPrefs = SS_prefs.getDefaultBranch('extensions.swaksmack.');
							maxUrlLength = defPrefs.getIntPref('maxurllength_intpref');
							SS_prefs.setIntPref(SMACK_MAXLENGTH, maxUrlLength);
						}
						var clippedUrlEnd=SS_getPreference(SMACK_TRUNCURL);
						if (maxUrlLength > 0 && element.nodeValue.length > maxUrlLength){
							var replacelength = element.nodeValue.length;
							var l1 = clippedUrlEnd.length;
							if (l1 == maxUrlLength) l1=0;
							var front = element.substringData(0, maxUrlLength-l1);
							front = front+clippedUrlEnd;
							var tn = doc.createTextNode(front);
							element.parentNode.replaceChild(tn,element.parentNode.firstChild);
						}
					}

					function externalLinks(doc) {
						if (doc == null) doc = content.document;
						if (!doc.getElementsByTagName) return;
						var anchors = doc.getElementsByTagName("a");
						//alert("links len " + anchors.length);
						for (var i=0; i<anchors.length; i++) {
							var anchor = anchors[i];
							if (anchor.getAttribute("href") &&
							anchor.getAttribute("rel") == "external")
							anchor.target = "_blank";
						}
					}

					function commentSpellCheck(doc) {
						if (doc == null) doc = content.document;
						var commentdiv = doc.getElementById(SMACK_OUTWITCOMMENTDIV);
						if (commentdiv != null) {
							commentdiv.spellcheck = true;
						}
					}

					function registerSmackChatListeners(doc) {
						//reset flags
						swaksmack.productListenerAdded = false;

						var chatDiv = doc.getElementById('chat');

						if (chatDiv != null){
							chatDiv.addEventListener('DOMNodeInserted', smackChatPostInserted, false);
							chatDiv.addEventListener('DOMAttrModified', smackChatPostAttrModified, false); //false
							chatDiv.addEventListener('DOMNodeRemoved', smackChatPostRemoved, false);
						}

						var guru=doc.getElementById('guruContainer');
						if (guru != null){
							guru.addEventListener('DOMAttrModified',smackChatGuruAttrModified,false);
						}
						var chatHeader = doc.getElementById('chatHeader');
						if (chatHeader != null) {
							chatHeader.addEventListener('dblclick', function(event) {
								toggleChat();
							}, false);
						}


						var msgCenterDiv = doc.getElementById('leftPanel');

						if (msgCenterDiv != null){

							if (SS_getPreference(SMACK_ENHANCEHIDEAVATARS))		 {
								msgCenterDiv.addEventListener('DOMNodeRemoved', function(event) {
									//alert('DOMNodeRemoved ' + event.target.id);
									smackPoll();
									if (SS_getPreference(SMACK_ENHANCEHIDEAVATARS))		 {
										var state = swaksmack.SS_JF.getState();
										if (state== SMACK_STATE_OUTWITRESULT || state == SMACK_STATE_OUTWITVOTE || state == SMACK_STATE_OUTWIT_VOTED || state == SMACK_STATE_NONGURUDEALSOLD) {
											//alert('DNR hide images');
											hideAllAvatarImages();
										}
									}
								}, false);



							}

							msgCenterDiv.addEventListener('DOMNodeRemoved', function(event) {
								var pid = null;
								try {
									pid = event.target.parentNode.id;
									/*
									if (pid == 'liveObjectTimer' || pid == 'cashBack' || pid == 'totalCost' || pid == 'jackpot' || pid == 'bonus' || pid == 'slider' ||
											pid =='smackPotTimer' || pid == 'sold_out_deal_timer' || pid == 'playerName') {
										return;
									}
									*/
									if (pid != 'retailPrice') {
										return;
									}
								}
								catch(x) {}
								
								if (pid == 'retailPrice') {
									addProductImageFlyout();
									
								}
								else {
									alert('left panel dnr event.target.parentNode.id ' + event.target.parentNode.id);
								}
							}, false);
						


						}


						var e1=doc.getElementsByName('user_guess');
						var guruinput;
						for (var i=0;i<e1.length;i++) {
							if (e1[i].name == 'user_guess') {
								guruinput = e1[i];
								break;
							}
						}
						if (guruinput != null) {
							if (SS_ggListenerAdded == false) {
								SS_ggListenerAdded = true;
								guruinput.addEventListener('dblclick', function(event) {
									launchCalcWindow();
								}, false);   //was true
							}
						}
						else {
							SS_ggListenerAdded = false;
						}


						///smackpot test stuff
						var spheaderDiv = doc.getElementById('smackPotHeader');

						if (spheaderDiv != null){
							
							var img = swaksmack.SmackShopDoc.createElement('img');
							img.setAttribute('src','chrome://swaksmack/skin/calculator.png');
							img.setAttribute('id','swaksmackSmackPotCalc');
							//img.src="chrome://swaksmack/skin/calculator.png";
							spheaderDiv.appendChild(img);
							
							img.addEventListener('mouseover', function(event) {
								event.target.setAttribute('src','chrome://swaksmack/skin/calculator_over.png');
							}, false);
							
							img.addEventListener('mouseout', function(event) {
								event.target.setAttribute('src','chrome://swaksmack/skin/calculator.png');
							}, false);
							
							img.addEventListener('click', function(event) {
								swakSmackPotCalc();
							}, false);
							
						}

						/////////////////////////////


					}
					
	function addPlayPause(doc) {
		if (doc == null) return;
		var cc = doc.getElementById('comment_comment');
		if (cc == null) return;
		
		var pcc = cc.parentNode;
		var cf = getElementsByClassName("clearFloat",pcc,doc);
		var pw = doc.getElementById('post_wait');
		var img = swaksmack.SmackShopDoc.createElement('img');
		img.setAttribute('src','chrome://swaksmack/skin/pause-chat.png');
		img.setAttribute('id','swaksmackChatPause');
		img.addEventListener('mouseover', function(event) {
			event.target.setAttribute('src','chrome://swaksmack/skin/pause-chat_over.png');
		}, false);
		
		img.addEventListener('mouseout', function(event) {
			event.target.setAttribute('src','chrome://swaksmack/skin/pause-chat.png');
		}, false);
		
		img.addEventListener('click', function(event) {
			//pause chat
			var paused = toggleChat();
		}, false);
		var jellyfishstrings = document.getElementById("swaksmack-strings");
		img.title = jellyfishstrings.getString("pause_tooltip");
		pcc.insertBefore(img,pw);
		
		var img2 = swaksmack.SmackShopDoc.createElement('img');
		img2.setAttribute('src','chrome://swaksmack/skin/play-chat.png');
		img2.setAttribute('id','swaksmackChatPlay');
		
		img2.addEventListener('mouseover', function(event) {
			event.target.setAttribute('src','chrome://swaksmack/skin/play-chat_over.png');
		}, false);
		
		img2.addEventListener('mouseout', function(event) {
			event.target.setAttribute('src','chrome://swaksmack/skin/play-chat.png');
		}, false);
		
		img2.addEventListener('click', function(event) {
			//resume chat
			var paused = toggleChat();		
		}, false);				
		//hide play for initialization
		img2.style.display='none';
		img2.title = jellyfishstrings.getString("play_tooltip");
		pcc.insertBefore(img2,pw);
		
		

	}				

  function swakSendPM(e) {
	    
    var ctx = swaksmack.postPopupNode;
    var ci = getCommentInfo(ctx);
    var chatNick = getElementChatNick(ci);
    var ref = chatNick[0].getAttribute('href');
    var paurl = 'http://www.jellyfish.com' + ref;
    var username = chatNick[0].textContent;
		
      initPMRequest(username, paurl,  window.content.document, e);		

  }

	function SwakSubmitProductQuery() {

		var product = swaksmack.SmackShopDoc.getElementById('productNameAnchor');
		if (product == null || product == 'undefined') return;
		var pt = product.textContent;

		var tu = new AmazonProductRequest(pt);  //was pt
		var amazonCB = {
			ondone : function(handle){
				var list = handle.amazonInfoList;
				if (list == null) return;
				var api = list.shift();
				alert('url: ' + api.prodURL + ' price: ' + api.prodPrice);
			},

			onerror : function(handle){
			}
		}
		tu.execute(amazonCB);
	}

					function smackChatPostAttrModified(event) {
						//alert('smackChatPostAttrModified entry');
						if (swaksmack.smackchatIdArray == null) {
							return;
						}
						
						//need to to proces the last added chat comment
						var processed = false;
						while (swaksmack.smackchatIdArray.length >0) {
							//alert('smackChatPostAttrModified length >0 ' + swaksmack.smackchatIdArray.length);
							//check content
							if (swaksmack.smackShopContentWindow == null || swaksmack.SS_JF.isUnknownState() == true || swaksmack.SmackShopDoc == null) {
								//alert('swaksmack state is unknown...fixing');
								if (isSmackShopArea(content.document) == true) {
									//alert('runtime reinitialization of smackShopContentWindow');
									swaksmack.smackShopContentWindow = gBrowser.contentWindow;
									swaksmack.SmackShopDoc = content.document;
								}
								else {
									var cw = SS_getSmackShoppingWindow();
									//alert('cw ' + cw);
									if (cw != null) {
										swaksmack.smackShopContentWindow = cw;
										swaksmack.SmackShopDoc = cw.document;
									}
								}
							}


							//alert('smackChatPostAttrModified');
							execute(swaksmack.smackchatIdArray.pop(), true, swaksmack.SmackShopDoc);
							if (processed == true) continue;
							
							swakCheckStateAlerts();

							if (swaksmack.SS_SBM.isMonitoring() == false) {
								swaksmack.SS_SBM.monitorState(SS_getPreference(SMACK_SBSALEINTERVAL));
							}
							updatePMLR();
							setChatSpeed();


							if (SS_ChatHeaderText != null ) {
								//reset chatHeader content
								if (SS_chatHeaderChange == true && swaksmack.SS_JF.isChatPaused() == false) {
									updateChatHeader(true);
								}

							}
							processed = true;
						}



					}

					function swakCheckStateAlerts() {
						if (SS_getPreference(SMACK_ENABKEALERTMONITORDELAY) == true) {
							setTimeout("smackPoll()",SS_alertTimeOut);
						}
						else {
							smackPoll();
						}
					}

					function smackChatPostInserted(event) {
						if (swaksmack.smackchatIdArray == null || swaksmack.SmackShopDoc == null) {
							return;
						}

						var cn = event.target.className;
						var id = event.target.id;
						if (id == null || id == 'undefined' || id == '') {
							return;
						}

						if (cn != null && (cn == 'commentFloatContainer' || cn == 'swaksmackUnhighlightUser' || cn =='swaksmackHighlightUser' 
							|| cn == 'swaksmackReply' || cn =='swaksmackAction' || cn == 'chatAvatar' || cn == 'swakAvatarImageContainer')) {
							return;
						}
						//alert(id + ' smackChatPostInserted cn ' + cn);
						while (swaksmack.smackchatIdArray.length >0) {execute(swaksmack.smackchatIdArray.pop(), true, swaksmack.SmackShopDoc);}


						swaksmack.smackchatIdArray.unshift(event.target);
					}

					//shared by both smack chat and LR
					function smackChatPostRemoved(event) {
						var cid = event.target.id;
						if (cid != null) {
							var cin = cid.indexOf('comment');
							if (cin != -1) {
								var hl = getElementSwakHighlightUser(event.target,swaksmack.SmackShopDoc);
								//var hl = getElementsByClassName('swaksmackHighlightUser',event.target);
								if (hl != null && hl[0] != null) {
									hl[0].removeEventListener('click', enhancedReply,false);
									hl[0].removeEventListener('click', enhancedHighlight,false);
									hl[0].removeEventListener('click', enhancedAction,false);
								}
								var uhl = getElementSwakUnhighlightUser(event.target,swaksmack.SmackShopDoc);
								//var uhl = getElementsByClassName('swaksmackUnhighlightUser',event.target);
								if (uhl != null && uhl[0] != null) {
									uhl[0].removeEventListener('click', enhancedReply,false);
									uhl[0].removeEventListener('click', enhancedHighlight,false);
									uhl[0].removeEventListener('click', enhancedAction,false);
								}
							}
							else {
								//alert(cin + ' element removed ' + cid);
							}
						}
					}

			function smackChatGuruAttrModified(event) {
				
				
							var gh = swaksmack.SmackShopDoc.getElementById('guruHeader');
							//alert('smackChatGuruAttrModified gh' +gh);
							if (gh != null) {
								var ssgc = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
								if (ssgc == null) {
									var img = swaksmack.SmackShopDoc.createElement('img');
									img.setAttribute('src','chrome://swaksmack/skin/calculator.png');
									img.setAttribute('id','swaksmackGuruCalc');
									gh.appendChild(img);
									
									img.addEventListener('mouseover', function(event) {
										event.target.setAttribute('src','chrome://swaksmack/skin/calculator_over.png');
									}, false);
									
									img.addEventListener('mouseout', function(event) {
										event.target.setAttribute('src','chrome://swaksmack/skin/calculator.png');
									}, false);
									
									img.addEventListener('click', function(event) {
										launchCalcWindow();
									}, false);
								}
								checkGuruGuess(false);
							}
				
				
				if (swaksmack.alertManager == null) {
					return;
				}
				swaksmack.alertManager.updateAlertState();
			}

			function registerLivingRoomChatListeners(doc) {
				var chatDiv = doc.getElementById('chat');

				if (chatDiv != null){
					chatDiv.addEventListener('DOMNodeInserted', livingRoomChatPostInserted, false);
					chatDiv.addEventListener('DOMAttrModified', livingRoomChatPostAttrModified, false);
					chatDiv.addEventListener('DOMNodeRemoved', smackChatPostRemoved, false);
				}

			}

			function livingRoomChatPostInserted(event) {
				if (swaksmack.smackLRIdArray == null || swaksmack.LivingRoomDoc == null) {
					return;
				}

				var cn = event.target.className;
				var id = event.target.id;
				if (id == null || id == 'undefined' || id == '') {
					return;
				}

		//		if (cn != null && (cn == 'commentFloatContainer' || cn == 'swaksmackUnhighlightUser' || cn =='swaksmackHighlightUser' || cn == 'swaksmackReply')) {
		//			return;
		//		}
		
				if (cn != null && (cn == 'commentFloatContainer' || cn == 'swaksmackUnhighlightUser' || cn =='swaksmackHighlightUser' 
						|| cn == 'swaksmackReply' || cn =='swaksmackAction' || cn == 'chatAvatar' || cn == 'swakAvatarImageContainer') ||
						cn == 'swaksmacktinyurlpreview') {
					return;
				}				

				while (swaksmack.smackLRIdArray.length >0) {execute(swaksmack.smackLRIdArray.pop(), true, swaksmack.LivingRoomDoc);}

				swaksmack.smackLRIdArray.unshift(event.target);

			}

			function livingRoomChatPostAttrModified(event) {
				if (swaksmack.smackLRIdArray == null || swaksmack.LivingRoomDoc == null) {
					return;
				}
				var cn = event.target.className;
				
				if (cn != null && (cn == 'largeBadge' ||
						 cn == 'chatAvatar' || cn == 'chatAvatarContainer' || cn == 'swakAvatarImageContainer')) {
					return;
				}
								
				//alert('livingRoomChatPostAttrModified ' + cn);
				
				//need to to proces the last added chat comment
				while (swaksmack.smackLRIdArray.length >0) {
					execute(swaksmack.smackLRIdArray.pop(), true, swaksmack.LivingRoomDoc);
					//externalLinks(swaksmack.LivingRoomDoc);
					setChatSpeed();
					updatePMLR();
				}
			}

			function checkGuruGuess(alertsEnabled) {
				if (alertsEnabled == null) alertsEnabled = true;

				var e1=swaksmack.SmackShopDoc.getElementsByName('user_guess');
				if (e1 != null) {
					var guruinput;
					for (var i=0;i<e1.length;i++) {
						if (e1[i].name == 'user_guess') {
							guruinput = e1[i];
							break;
						}
					}
					if (guruinput != null) {
						try {
								var ssgc = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
								if (ssgc != null) {
								  if (guruinput.style.display != 'none') {
										ssgc.style.display='';
									}
									else {
										ssgc.style.display='none';
									}
								}
							
						}
						catch(x){}
						if (SS_ggListenerAdded == false) {
							SS_ggListenerAdded = true;
	
							guruinput.addEventListener('dblclick', function(event) {
								launchCalcWindow();
							}, false);

							var gcon = swaksmack.SmackShopDoc.getElementById('guruContainer');
							if (gcon != null) {
								gcon.addEventListener('submit', function(event) {
									try {
										var ssgch = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
										if (ssgch != null && guruinput.style.display == 'none') {
											ssgch.style.display='none';
										}
											swakstats.incrementGuruGuessPlayed();
											this.removeEventListener('submit',arguments.callee,false);
									}
									catch (x) {
										swakAddException(x);
										//alert(x);
										}
								}, false);
							}
						}
						} else {
							SS_ggListenerAdded = false;
								var ssgch = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
								if (ssgch != null) {
									ssgch.style.display='none';
								}
						}

					} //end e1
					else {
						SS_ggListenerAdded = false;
						var ssgch = swaksmack.SmackShopDoc.getElementById('swaksmackGuruCalc');
						if (ssgch != null) {
							ssgch.style.display='none';
						}
					}

					////////////////////


					if (alertsEnabled && swakalerts.guruguessAlertAck == false && swaksmack.SmackShopDoc.getElementById(SMACK_OUTWITGURUGUESSDIV) != null) {
						var guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);
						swakalerts.guruguessAlertAck = true;

						if (guruguessAlertPref == "audio" || guruguessAlertPref == "both"){
							var soundFile = SS_getPreference(SMACK_AUDIOSOUND_GURUGUESS);
							if (soundFile == null || soundFile == '') {
								soundFile = AUDIO_DIR + DEFAULT_SOUND;
							}
							swaksmack.audioManager.playAudioAlert(soundFile);
						}
						if (guruguessAlertPref == "alert" || guruguessAlertPref == "both"){
							var leftPanel = swaksmack.SmackShopDoc.getElementById('leftPanel');
							if (leftPanel != null) {
								leftPanel.addEventListener('click',  function(event) {
									swaksmack.alertManager.alertWindow.close();
									//remove this event listener
									this.removeEventListener('click',arguments.callee,false);
								}, false);
							}
							swaksmack.alertManager.swakAlert(SMACK_ALERT_GURUGUESS, true, 60000, true);
						} 
						else if (swaksmack.SmackShopDoc.getElementById(SMACK_OUTWITGURUGUESSDIV) == null) {
							swakalerts.guruguessAlertAck = false;
						}
					}
					else {
						//this constantly entered during a SD show after guess is in
						//alert(SS_guruguessAlertAck + ' (SS_guruguessAlertAck) checkGuruGuess failed to find GG (div) ' + SS_doc.getElementById(SMACK_OUTWITGURUGUESSDIV));
					}
				}

					var SS_oldState = null;
					var SS_outwitOptInCounted = false;
					var SS_outwitVoteCounted = false;
					var SS_outwitSelected = false;
					var SS_smackpotEntryCounted = false;
					var SS_guruguessmade = false;
					var SS_smackpotCoinsWon = false;
					var SS_ouwitPointWon = false;
					var SS_outwitOptinSubmitted = false;
					var SS_outwitResultInfoProcessed = false;
					
					
					var TEMPERRORTRACK = false;

					function smackPoll() {
						
						try {
						
						var cState = swaksmack.SS_JF.getState();
						swaksmack.SS_SBM.refreshState();
						
						if (cState != SMACK_STATE_OUTWITRESULT) {
							swakOTSEvalCount = 0;
							SS_outwitResultInfoProcessed = false;
						}
						
						if (cState == SMACK_STATE_OUTWITRESULT || cState == SMACK_STATE_NONGURUDEAL
						|| cState == SMACK_STATE_GURUGUESSSOLD || cState == SMACK_STATE_SMACKPOT_BETCLOSED
						|| cState == SMACK_STATE_OUTWITMISSED) {

							swakalerts.outwitAlertAck = false;
							swakalerts.outwitVoteAck = false;
							swakalerts.smakpotAlertAck = false;
							swakalerts.guruguessAlertAck = false;

							SS_ggListenerAdded = false;

							//reset
							SS_outwitOptInCounted = false;
							SS_outwitVoteCounted = false;
							SS_outwitSelected = false;
							SS_guruguessmade = false;
							SS_smackpotCoinsWon = false;
							SS_smackpotEntryCounted = false;
							SS_outwitOptinSubmitted = false;

							if (cState == SMACK_STATE_PREVIEW) {
								swaksmack.coinsWonDuringShow = 0;
							}


							//still want to process result below
							if (cState != SMACK_STATE_OUTWITRESULT && cState != SMACK_STATE_GURUGUESSSOLD) {
								SS_ouwitPointWon = false;
								return;
							}
						}
						

						
						//another safety check since we don't have a real state machine to eval transistions
						if (SS_oldState == SMACK_STATE_NONGURUDEAL && cState == SMACK_STATE_OUTWITOPTIN) {

							swakalerts.outwitAlertAck = false;
							swakalerts.outwitVoteAck = false;
							swakalerts.smakpotAlertAck = false;
							swakalerts.guruguessAlertAck = false;

							SS_outwitOptInCounted = false;
							SS_outwitVoteCounted = false;
							SS_outwitSelected = false;
							SS_smackpotEntryCounted = false;
							SS_guruguessmade = false;
							SS_smackpotCoinsWon = false;
							SS_ouwitPointWon = false;
							SS_outwitOptinSubmitted = false;
						}

						var outwitAlertPref = "none";
						var outwitVoteAlertPref = "none";
						var guruguessAlertPref = "none";
						var smackpollAlertPref = "none";
						var alertsEnabled = true;
						try {
							outwitAlertPref = SS_getPreference(SMACK_OUTWITALERT);
							outwitVoteAlertPref = SS_getPreference(SMACK_OUTWITVOTEALERT);
							guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);
							smackpollAlertPref = SS_getPreference(SMACK_SMACKPOTALERT);
							alertsEnabled = SS_getPreference(SMACK_ALERTGLOABLEENABLE);
						}
						catch(Exception){
							swakAddException(Exception);
							//alert('Error with alert options.  Notify the swaksmack development team.');
						}



						//alert('smackpoll cstate: ' + cState);

						if (cState == SMACK_STATE_OUTWITOPTIN){
							if (alertsEnabled && outwitAlertPref != "none" && swakalerts.outwitAlertAck == false) {
								swakalerts.outwitAlertAck = true;
								SS_outwitSelected = false;
								if (outwitAlertPref == "both" || outwitAlertPref == "audio"){
									var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWIT);
									if (soundFile == null || soundFile == '') {
										soundFile = AUDIO_DIR + DEFAULT_SOUND;
									}
									swaksmack.audioManager.playAudioAlert(soundFile);
								}
								if (outwitAlertPref == "both" || outwitAlertPref == "alert"){
									var capans = swaksmack.SmackShopDoc.getElementById('captcha_answer');
									if (capans != null) {
										capans.addEventListener('click',  function(event) {
											swaksmack.alertManager.alertWindow.close();
											//remove this event listener
											this.removeEventListener('click',arguments.callee,false);
										}, false);
									}

									swaksmack.alertManager.swakAlert(SMACK_ALERT_OUTWITOPTIN, true, 60000, true);
								}
							}

							var owc = swaksmack.SmackShopDoc.getElementById('outwitContainer');
							if (owc != null) {
								owc.addEventListener('submit',  function(event) {
									SS_outwitOptinSubmitted = true;
									//remove this event listener
									this.removeEventListener('submit',arguments.callee,false);
								}, true);
							}

						}
						else if (cState == SMACK_STATE_OUTWITVOTE){
							if (alertsEnabled && outwitVoteAlertPref != "none" && swakalerts.outwitVoteAck == false) {
								swakalerts.outwitVoteAck = true;
								swakalerts.outwitAlertAck = false;
								swakalerts.smakpotAlertAck = false;
								swakalerts.guruguessAlertAck = false;
								//check if already checked
								var owc = swaksmack.SmackShopDoc.getElementById('outwitContainer');
								if (owc == null) return;
								var anschecked = getElementsByClassName('outwitAnswerChecked', owc,swaksmack.SmackShopDoc);
								if (anschecked != null && anschecked[0] != null) {
									return;
								}
								SS_outwitSelected = false;
								if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "audio") {
									var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWITVOTE);
									if (soundFile == null || soundFile == '') {
										soundFile = AUDIO_DIR + DEFAULT_SOUND;
									}
									swaksmack.audioManager.playAudioAlert(soundFile);
								}
								if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "alert") {
									var leftPanel = swaksmack.SmackShopDoc.getElementById('leftPanel');
									if (leftPanel != null) {
										leftPanel.addEventListener('click',  function(event) {
											swaksmack.alertManager.alertWindow.close();
											//remove this event listener
											this.removeEventListener('click',arguments.callee,false);
										}, false);
									}
									swaksmack.alertManager.swakAlert(SMACK_ALERT_OUTWITVOTE, true, 60000, true);
								}
							}
						}
						else if (cState == SMACK_STATE_SMACKPOT_BETOPEN){
							if (alertsEnabled && smackpollAlertPref != "none" && swakalerts.smakpotAlertAck == false) {

								swakalerts.smakpotAlertAck = true;
								if (smackpollAlertPref == "both" || smackpollAlertPref == "audio") {
									var soundFile = SS_getPreference(SMACK_AUDIOSOUND_SMACKPOTBET);
									if (soundFile == null || soundFile == '') {
										soundFile = AUDIO_DIR + DEFAULT_SOUND;
									}
									swaksmack.audioManager.playAudioAlert(soundFile);
								}
								if (smackpollAlertPref == "both" || smackpollAlertPref == "alert"){
									//alert('smack pot alert');
									var leftPanel = swaksmack.SmackShopDoc.getElementById('leftPanel');
									if (leftPanel != null) {
										leftPanel.addEventListener('click',  function(event) {
											swaksmack.alertManager.alertWindow.close();
											//remove this event listener
											this.removeEventListener('click',arguments.callee,false);
										}, false);
									}
									swaksmack.alertManager.swakAlert(SMACK_ALERT_SMACKPOTGUESS, true, 60000, true);
								}
							}
						}
						else if (cState == SMACK_STATE_GURUGUESSENTER){
							//alert('REMOVE check guru state smack poll state ' + cState);
							checkGuruGuess(alertsEnabled);
						}
						else if (SS_outwitOptinSubmitted == true && SS_outwitOptInCounted == false && cState == SMACK_STATE_OUTWITOPTINENTERED){
							SS_outwitOptInCounted = true;
							SS_outwitOptinSubmitted = false;
							swakstats.incrementOutwitOptIn();
						}
						else if (SS_outwitVoteCounted == false && cState == SMACK_STATE_OUTWIT_VOTED){
							SS_outwitVoteCounted = true;
							swakstats.incrementOutwitVote();
						}
						else if (SS_smackpotEntryCounted == false && cState == SMACK_STATE_SMACKPOT_BETMADE){
							//alert('increment sp bet made');
							SS_smackpotEntryCounted = true;
							swakstats.incrementSmackPotPlayed();
							try {
								var bet = swaksmack.SmackShopDoc.getElementById('myBet');
								if (bet != null) {
									var c = bet.textContent;
									var coins = parseInt(c);
									swakstats.incrementSmackPotBet(coins);
								}
							}
							catch(x){
								swakAddException(x);	
							}
						}
						else if (SS_outwitSelected == false && cState == SMACK_STATE_OUTWITCONTESTANTSELECTED){
							SS_outwitSelected = true;
							
							var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWITCONTESTANT);
							swaksmack.audioManager.playAudioAlert(soundFile);
							
							try {
								var pnid = swaksmack.SmackShopDoc.getElementById('playerName');
								if (pnid != null) {
									var nickname = swaksmack.SS_JF.getNickName();
									if (nickname == pnid.textContent) {
										swakstats.incrementOutwitSelected();
									}
								}
							}
							catch(x){
								swakAddException(x);	
							}


						}
						else if(SS_smackpotCoinsWon == false && cState == SMACK_STATE_SMACKPOT_RESULTS) {
							SS_smackpotCoinsWon = true;
							var coinsoundplay = false;
							try {
								var coins = swaksmack.SS_JF.getSmackPotCoinsWon();
								swakstats.incrementSmackPotCoinsWon(coins);
								swaksmack.coinsWonDuringShow +=coins;
								swaksmack.coinsWonOnLastItem = coins;
								swaksmack.coinsWonDuringSession +=coins;
								if (coins >1) {
									var soundFile = SS_getPreference(SMACK_AUDIOSOUND_SMACKPOTWON);
									swaksmack.audioManager.playAudioAlert(soundFile);
									coinsoundplay = true;
								}
								//alert('coins won ' + coins);
							}
							catch (x) {
								swakAddException(x);
							}
							if (!coinsoundplay) {
							var soundFile = SS_getPreference(SMACK_AUDIOSOUND_ITEMSOLD);
							if (soundFile == null || soundFile == '') {
								soundFile = AUDIO_DIR + DEFAULT_SOUND;
							}
								swaksmack.audioManager.playAudioAlert(soundFile);
							}
							if (SS_getPreference(SMACK_DISPLAYSOLDINFO)) {
								insertSoldPrice(false);
							}
							
						}
						else if (cState == SMACK_STATE_OUTWITRESULT) {
							if (SS_ouwitPointWon == false) {
								SS_ouwitPointWon = true;
								var winner = swaksmack.SS_JF.isGuruWinner();
								//alert('outwit result ' + winner);
								if (winner == true) {
									swakstats.incrementOutwitPoint();
									var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWITPOINT);
									swaksmack.audioManager.playAudioAlert(soundFile);
									
								}
								else {
									var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWITRESULT);
									swaksmack.audioManager.playAudioAlert(soundFile);
								}
							}
							if (SS_getPreference(SMACK_DISPLAYOTSINFO)) {
								insertOutwitInfo();
							}
						}
						else if (cState == SMACK_STATE_GURUGUESSWHEELSPIN) {
							if (alertsEnabled && swakalerts.wheelSpinAlertAck == false) {
								swakalerts.wheelSpinAlertAck = true;
								
									var nickname = swaksmack.SS_JF.getNickName();
									var c = swaksmack.SS_JF.getWheelContestant();
									if (c == nickname) {
										if (guruguessAlertPref == "audio" || guruguessAlertPref == "both"){
											var soundFile = SS_getPreference(SMACK_AUDIOSOUND_WHEELSPIN);
											swaksmack.audioManager.playAudioAlert(soundFile);
										}
										if (guruguessAlertPref == "alert" || guruguessAlertPref == "both"){
											swaksmack.alertManager.swakAlert(SMACK_ALERT_GURUWHEELSPIN, true, 60000, true);
										}
									}
								
							}
						}
						else if (SS_smackpotCoinsWon == false && cState == SMACK_STATE_GURUGUESSSOLD) {
							SS_smackpotCoinsWon = true;
							//alert('sp --SMACK_STATE_GURUGUESSSOLD');
							var soundFile = SS_getPreference(SMACK_AUDIOSOUND_ITEMSOLD);
							if (soundFile == null || soundFile == '') {
								soundFile = AUDIO_DIR + DEFAULT_SOUND;
							}
							swaksmack.audioManager.playAudioAlert(soundFile);
							if (SS_getPreference(SMACK_DISPLAYSOLDINFO)) {
								insertSoldPrice(true);
							}
						}
					} //end try
					catch(x) {
						if (TEMPERRORTRACK == false) {
							TEMPERRORTRACK = true;
							swakAddException(x);
							alert("Extension Alert Error, please notify the developers: " + x);
						}
					}
					}
					
					
					var swakOTSErrorAck = false;
					function insertOutwitInfo() {
						if (SS_outwitResultInfoProcessed == true) return;
						try {
							if (swaksmack.SmackShopDoc == null) {
								return;
							}
							var oc = swaksmack.SmackShopDoc.getElementById('outwitContainer');
							if (oc == null) {
								return;
							}
							var otsrt = getElementsByClassName('outwitResults',swaksmack.SmackShopDoc,swaksmack.SmackShopDoc);
							if (otsrt == null || otsrt[0] == null) {
								return;
							}
							var otsresult = swakBuildOTSResult();
							
							
							if (otsresult == null) {
								//alert('null increment ' + swakOTSEvalCount);
								//swakOTSEvalCount++;
								//save it just in case
								swakOTSInnerHtml = oc.innerHTML;
								SS_outwitResultInfoProcessed = true;
								return;
							}
							
							if (SS_getPreference(SMACK_DISPLAYEHANCEDOTSINFO)) {
								var rows = oc.getElementsByTagName("tr");
								var windex = swakGetOTSWinIndex(otsresult.answers,otsresult.winningAnswers,rows);	
							}
							
							swakOTSInnerHtml = oc.innerHTML;
							//swakOTSInnerHtml = chtml;
							if (otsresult.numVoters == null || otsresult.numVoters == -1) {
								swakOTSInnerHtml = swakOTSInnerHtml + "<span class=\"swakOTSVoters\">Estimated number of voters: " + "More than 3, less than 1 million?" + "</span>";
							}
							else {
								swakOTSInnerHtml = swakOTSInnerHtml + "<span class=\"swakOTSVoters\">Estimated number of voters: " + otsresult.numVoters + "</span>";
							}
							if (SS_getPreference(SMACK_DISPLAYEHANCEDOTSINFO)) {
								var cdate = new Date();
						  	swakOTSInnerHtml = swakOTSInnerHtml + "<br/><span class=\"swakOTSDate\">" + cdate.formatDate("D F jS Y h:i A"); + "</span>";
							}
							oc.innerHTML = swakOTSInnerHtml;
							//swakOTSInnerHtml = chtml;
							swakOTSInnerHtml = swakOTSInnerHtml.replace(/[/]img[/]shoppers[/]/g, 'http://www.jellyfish.com/img/shoppers/');
							swakOTSInnerHtml = swakOTSInnerHtml.replace(/[/]smack[/]images[/]/g, 'http://www.jellyfish.com/smack/images/');
							swakOTSInnerHtml = swakOTSInnerHtml.replace(/\"[/]shoppers[/]/g, '\"http://www.jellyfish.com/shoppers/');
							swakOTSInnerHtml = swakOTSInnerHtml.replace(/<h2>/g, '<h2 class=\"swakOTSVoters\">');
							otsresult.innerHTML = swakOTSInnerHtml;
							swaksmack.lastOTSResult = otsresult;
							addOTSResult(otsresult);
							SS_outwitResultInfoProcessed = true;
						}
						catch(x) {
							if (swakOTSErrorAck == false) {
								swakOTSErrorAck = true;
								alert('Error processing OTS, I will keep trying ' + x);
								swakAddException(x);
								SS_outwitResultInfoProcessed = false;
							}
						}
					}
					
					function addOTSResult(otsresult){
				//		alert('addOTSResult entry ' + otsresult);
						if (otsresult == null) return;
						if (swakOTSList == null) {
							swakOTSList = new Array();
						}
						var maxsize = SS_getPreference(SMACK_STAT_OW_MAXLISTSIZE);
						if (maxsize == null) maxsize = 10;
						if (swakOTSList.length >=maxsize){
							swakOTSList.shift();
						}
						
						swakOTSList.push(otsresult);
					//	alert('addOTSResult len post push ' + swakOTSList.length);
					}
					
					/*
					//keep for debug of FF freeze problem 122107
					function insertOutwitInfo_ORG() {
						if (SS_outwitResultInfoProcessed == true) return;
						if (swakOTSEvalCount >=5) {
							swakAddException('insertOutwitInfo swakOTSEvalCount >=5');
							return;
						}
						try {
							swakAddException("IOI try entry");
							if (swaksmack.SmackShopDoc == null) {
								swakAddException("IOI smackshopdoc is null " + swakOTSEvalCount);
								swakOTSEvalCount++;
								return;
							}
							var oc = swaksmack.SmackShopDoc.getElementById('outwitContainer');
							if (oc == null) return;
							swakAddException("IOI pre get swakOTSVoters");
							var swakotsvote = getElementsByClassName('swakOTSVoters',oc);
							if (swakotsvote != null && swakotsvote[0] != null) return;
							swakAddException("IOI pre build swakBuildOTSResults");
							swaksmack.lastOTSResult = swakBuildOTSResult();
							swakAddException("IOI post build swakBuildOTSResults");
							//test
							//swaksmack.lastOTSResult = null;
							if (swaksmack.lastOTSResult == null) {
								swakAddException("IOI swaksmack.lastOTSResult " + swakOTSEvalCount);
								//alert('null increment ' + swakOTSEvalCount);
								swakOTSEvalCount++;
								//save it just in case
								swakOTSInnerHtml = oc.innerHTML;
								return;
							} 
							//
							
							
							swakAddException("IOI pre get rows");
							var rows = oc.getElementsByTagName("tr");
							swakAddException("IOI post get rows");
							var windex = swakGetOTSWinIndex(swaksmack.lastOTSResult.answers,swaksmack.lastOTSResult.winningAnswers,rows);	
							swakAddException("IOI post get swakGetOTSWinIndex");
							var chtml = oc.innerHTML;
							if (swaksmack.lastOTSResult.numVoters == null || swaksmack.lastOTSResult.numVoters == -1) {
								swakAddException("IOI bad numvoters");
								chtml = chtml + "<span class=\"swakOTSVoters\">Estimated number of voters: " + "More than 3, less than 1 million?" + "</span>";
							}
							else {
								swakAddException("IOI good numvoters");
								chtml = chtml + "<span class=\"swakOTSVoters\">Estimated number of voters: " + swaksmack.lastOTSResult.numVoters + "</span>";
							}
							swakAddException("IOI pre formatDate");
							swakAddException("IOI pre create date");
							var cdate = new Date();
							chtml = chtml + "<br/><span class=\"swakOTSDate\">" + cdate.formatDate("D F jS Y h:i A"); + "</span>";
							swakAddException("IOI post formatDate");
							
							oc.innerHTML = chtml;
							//save results as html fragment
							swakOTSInnerHtml = chtml;
							swakAddException("IOI pre inner replace");
							swakOTSInnerHtml = swakOTSInnerHtml.replace(/[/]img[/]shoppers[/]/g, 'http://www.jellyfish.com/img/shoppers/');
							swakOTSInnerHtml = swakOTSInnerHtml.replace(/[/]smack[/]images[/]/g, 'http://www.jellyfish.com/smack/images/');
							swakAddException("IOI pre inner replace images");
							swakOTSInnerHtml = swakOTSInnerHtml.replace(/\"[/]shoppers[/]/g, '\"http://www.jellyfish.com/shoppers/');
							swakOTSInnerHtml = swakOTSInnerHtml.replace(/<h2>/g, '<h2 class=\"swakOTSVoters\">');
							swakAddException("IOI post inner replace h2");
							if (windex != null) {
								swakOTSEvalCount = 0;
								SS_outwitResultInfoProcessed = true;
								swakAddException("IOI windex not null " + SS_outwitResultInfoProcessed);
							}
							else {
								swakOTSEvalCount++;
								swakAddException("IOI windex null " + swakOTSEvalCount);
							}
							//alert(swakOTSInnerHtml);
						}
						catch (x) {
							if (swakAddExceptionAck == false) {
								alert('Please send this error to Mindstorm: Insert OTS Info ' + x);
							}
							swakOTSEvalCount++;
							swakAddException(x);
							SS_outwitResultInfoProcessed = false;
						}
					}
					*/
					
					
					function insertSoldPrice(guruguess) {
						if (guruguess == null) guruguess = false;
						try {
							var bd = swaksmack.SmackShopDoc.getElementById('bestDeal');
							if (bd == null) return;
							var swakSold = getElementsByClassName('swakBestDealSoldPrice',bd,swaksmack.SmackShopDoc);
							if (swakSold != null && swakSold[0] != null) return;
							var retailPrice = swaksmack.SS_JF.getRetailPrice();
			  			var discountPercent = swaksmack.SS_JF.getDiscount();
			  			var salePrice = swaksmack.SS_JF.getSalePrice(retailPrice,discountPercent);
			  			if (salePrice == null) {
			  				return;
			  			}
			  			var chtml = bd.innerHTML;
							chtml = chtml + "<span class=\"swakBestDealSoldPrice\">Sold: $" + salePrice +"</span>";
							bd.innerHTML = chtml;
							var deal = swaksmack.SmackShopDoc.getElementById('deal');
							if (deal != null) {
								swakSoldInnerHtml = deal.innerHTML;

							}
							if (guruguess == true) {
								var guru = swaksmack.SmackShopDoc.getElementById('guru');
								if (guru == null) return;
								swakGuruWinnersInnerHtml = "<div id=\"guruContainer\">" +guru.innerHTML + "</div>";
								swakSoldInnerHtml = swakSoldInnerHtml + swakGuruWinnersInnerHtml;
							}
							
							//save smackpot
							var sp = swaksmack.SmackShopDoc.getElementById('smackPotResults');
							if (sp != null) {
								//alert('adding sp results');
								//swakSmackPotSoldInnerHtml = "<div id=\"swakSmackPotResultsContainer\"><div id=\"smackPot\" class=\"swakSmackPotSold\"><table id=\"smackPotTable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
								swakSmackPotSoldInnerHtml = "<div id=\"swakSmackPotResultsContainer\"><div id=\"smackPot\" class=\"swakSmackPotSold\"><table id=\"smackPotResults\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
								swakSmackPotSoldInnerHtml = swakSmackPotSoldInnerHtml + sp.innerHTML + "</table></div></div>";
								//swakSmackPotSoldInnerHtml = swakSmackPotSoldInnerHtml + "</div>";
								
								
								swakSmackPotSoldInnerHtml = swakSmackPotSoldInnerHtml.replace(/[/]img[/]shoppers[/]/g, 'http://www.jellyfish.com/img/shoppers/');
								swakSmackPotSoldInnerHtml = swakSmackPotSoldInnerHtml.replace(/[/]smack[/]images[/]/g, 'http://www.jellyfish.com/smack/images/');
								swakSmackPotSoldInnerHtml = swakSmackPotSoldInnerHtml.replace(/\"[/]shoppers[/]/g, '\"http://www.jellyfish.com/shoppers/');
								
								
//								swakSoldInnerHtml = swakSoldInnerHtml + swakSmackPotSoldInnerHtml;
							}
							else {
								swakSmackPotSoldInnerHtml = null;
							}
							
							swakSoldInnerHtml = swakSoldInnerHtml.replace(/[/]img[/]shoppers[/]/g, 'http://www.jellyfish.com/img/shoppers/');
							swakSoldInnerHtml = swakSoldInnerHtml.replace(/[/]smack[/]images[/]/g, 'http://www.jellyfish.com/smack/images/');
							swakSoldInnerHtml = swakSoldInnerHtml.replace(/\"[/]shoppers[/]/g, '\"http://www.jellyfish.com/shoppers/');
							swakSoldInnerHtml = swakSoldInnerHtml.replace(/<h2 id=\"dealProductName\">/g, '<h2 id=\"dealProductName\" class=\"swakSoldInfo\">');
							
							
		  			}
		  			catch (x) {
		  				swakAddException(x);
		  				//alert('insertSoldPrice error ' + x);
		  			}
					}
					
					function swakInsertDealEndTime() {
						var sdi = swaksmack.SmackShopDoc.getElementById('swakDealInfo');
						if (sdi != null) return;
						
						try {
							var d = swaksmack.SS_JF.getDealDuration();
							var s = swaksmack.SS_JF.getDealStartedAt();
							var ed = getDealEndTime(s,d);
							var fdate = ed.formatDate("h:i:s A");
							//alert('deal end time: '+ fdate);
							var dd = swaksmack.SmackShopDoc.getElementById('dealDetails');
							if (dd == null) return;
							var swakdi = swaksmack.SmackShopDoc.createElement("div");
							swakdi.textContent = 'Deal End Time: ' + fdate;
							swakdi.setAttribute('id','swakDealInfo');
							swakdi.className = 'swakDealInfoDate';
							dd.appendChild(swakdi);
							
						}
						catch(x) {
							swakAddException(x);
						}
					
					}

					function hideAllAvatarImages() {

						var ha = "/img/shoppers/avatars/.*";
						var regExp = new RegExp(ha,"ig");
						var img = null;
						for(i=swaksmack.SmackShopDoc.images.length-1;i>=0;i--){
							img = swaksmack.SmackShopDoc.images[i];
							var isrc = swaksmack.SmackShopDoc.images[i].src;
							if (isrc != null && img.style.display != 'none') {
								var hide = regExp.test(isrc);
								if (hide) {
									img.style.display='none';
								}
							}

						}
						swaksmack.SmackShopDoc.close();

					}

					// swaksmack context menu stuff

					function swakContextVisibilityOn() {
						var menuitems = ['swaksmack-context-menu',
						'contextmenu-addkeywords',
						'contextmenu-listkeywords',
						'contextmenu-clearkeywords',
						'contextmenu-chatdisplayhl'];
						for (var i=menuitems.length-1;i>=0;i--){
							document.getElementById(menuitems[i]).setAttribute('hidden','false');
						}
					}

					function swakContextShowing() {
						//alert('contextShowing');
						var menuitem = document.getElementById("contextmenu-addkeywords");
						if (gContextMenu.isTextSelected) {
							var keyword;
							if (gContextMenu.searchSelected)
							keyword = gContextMenu.searchSelected();
							else
								keyword = getBrowserSelection();
								if (keyword.length > SS_keywordDisplayLength)
								keyword = keyword.substr(0,SS_keywordDisplayLength-1) + "...";
								var displaytext = "Add \"" + keyword + "\" to SwakSmack highlights.";
								menuitem.setAttribute("label", displaytext);
								menuitem.setAttribute("hidden","false");
							}
							else {
								menuitem.setAttribute("hidden","true");
							}
						}

						function chatAddKeywords() {
							//alert('Do keyword stuff');
							var keyword = "";
							if (gContextMenu.onTextInput)
							{
								//alert('Do keyword stuff on textinput');
								keyword = document.popupNode;
								keyword = keyword.value.substring(keyword.selectionStart, keyword.selectionEnd);
								if (keyword.length>SS_keywordDisplayLength)
								keyword = keyword.substr(0,SS_keywordDisplayLength-1);
							}
							else
								{
									if (gContextMenu.searchSelected)
									keyword = gContextMenu.searchSelected();
									else
										keyword = getBrowserSelection();
										if (keyword.length == 0)
										{
											//do nothing? /?an alert?
											return;
										}
									}
									if (keyword.length>0)
									{
										//alert(keyword);
										SS_dynamicKeywords.push(keyword);
						//				JF_keywordlistRegExp = null;
						//				JF_usernamelistRegExp = null;
										JF_usernameArray = [];
										JF_keywordArray = [];
										highlightExistingComments(content.document);
									}

								}

								function toggleDisplayHighlighted() {
									if (isSmackShopArea(content.document)) {
										swaksmack.smackCommentsHidden = !swaksmack.smackCommentsHidden;
										toggleHighlightedCommentDisplay(content.document,swaksmack.smackCommentsHidden);
										updateDisplayHighlightedUI(content.document);
									}
									//for now no show highlight only in LR
									/*
									else if (isLRArea(content.document)) {
									swaksmack.lrCommentsHidden = !swaksmack.lrCommentsHidden;
									toggleHighlightedCommentDisplay(content.document,swaksmack.lrCommentsHidden);
									updateDisplayHighlightedUI(content.document);

									}
									*/


								}

								function updateDisplayHighlightedUI(doc) {
									if (doc == null) return;
									if (isSmackShopArea(doc) && gBrowser.contentWindow == swaksmack.smackShopContentWindow) {
										var sbitem = document.getElementById('ss-sb-pu-chatdisplayhl');
										if (sbitem != null) {
											sbitem.setAttribute('checked',swaksmack.smackCommentsHidden);
										}
										var cmitem = document.getElementById('contextmenu-chatdisplayhl');
										if (cmitem != null) {
											cmitem.setAttribute('checked',swaksmack.smackCommentsHidden);
										}
										SS_chatHeaderChange = true;
										updateChatHeader(!swaksmack.SS_JF.isChatPaused());
										//		alert('smack set check hidden ' + hidden);
									}
									//for now no show highlight only in LR
									/*
									else if (isLRArea(doc) && gBrowser.contentWindow != swaksmack.smackShopContentWindow) {
									var sbitem = document.getElementById('ss-sb-pu-chatdisplayhl');
									if (sbitem != null) {
									sbitem.setAttribute('checked',swaksmack.lrCommentsHidden);
									}
									var cmitem = document.getElementById('contextmenu-chatdisplayhl');
									if (cmitem != null) {
									cmitem.setAttribute('checked',swaksmack.lrCommentsHidden);
									}
									//	alert('lr set check hidden ' + hidden);
									}
									*/


								}

								function SwakProductSearchAmazon() {
									queryExternal(SEARCH_AMAZON_URL);
								}

								function SwakProductSearchEbay() {
									queryExternal(SEARCH_EBAY_URL);
								}
								
								function SwakProductSearchFroogle() {
									queryExternal(SEARCH_FROOGLE_URL);
								}
								
								function SwakProductSearchSmackOfShame() {
									//queryExternal(SEARCH_SMACKOSHAME_URL);
									querySmackOfShameExternal();
								}
								
								function SwakShowLastOTS() {
									//alert(swakOTSList + ' () previous ots results '+ swakOTSInnerHtml);
									if (swakOTSList == null) return;
									var oro = swakOTSList[swakOTSList.length-1];
									if (oro == null) return;
									swakOTSListIndex = swakOTSList.length-1;
									swakOTSInnerHtml = oro.innerHTML;
									
									var nbd = "'true'";
									var pbd = "'true'";
									if (swakOTSList.length > 1) {
										pbd = "'false'";
									}

									var otswindow=window.open('','SwakSmack OTS Result','height=590,width=410,resizable=yes,scrollbars=yes');
									//otswindow.document.location.protocol="http:";
									//otswindow.document.location.host="www.jellyfish.com";
									otswindow.title = "SwakSmack OTS Result";
   								otswindow.document.write("<HTML>");
   								otswindow.document.write("<HEAD>");
   								otswindow.document.write("<link href=\"http://www.jellyfish.com/smack/stylesheets/smackV2.css?1192206863\" media=\"screen\" rel=\"Stylesheet\" type=\"text/css\">");
   								otswindow.document.write("<link href=\"chrome://swaksmack/skin/swaksmack.css\" media=\"screen\" rel=\"Stylesheet\" type=\"text/css\">");
   								otswindow.document.write("<script src=\"chrome://swaksmack/content/otsresult.js\" type=\"text/javascript\"></script>");
   								otswindow.document.write("</HEAD>");
   								otswindow.document.write("<BODY>");
   								otswindow.document.write("<DIV id=\"leftPanel\">");
   								otswindow.document.write("<DIV id=\"liveObjectContainer\" class=\"swakotsresultloc\">");
   								otswindow.document.write(swakOTSInnerHtml);
   								otswindow.document.write("</DIV>");
   								otswindow.document.write("</DIV>");
   								otswindow.document.write("<DIV id=\"swakotsresultsclose\">");
   								otswindow.document.write("<CENTER>");
   								otswindow.document.write("<input type='button' id=\"swakotsclose\" value='Close' onclick='self.close()'/>");
   								//otswindow.document.write("<input type='button' id=\"swakotsprevious\" value='Previous' disabled=" + pbd + " onclick='swakOTSPrevious(self)'/>");
   								//otswindow.document.write("<input type='button' id=\"swakotsnext\" value='Next' disabled=" + nbd + " onclick='swakOTSNext(self)'/>");
   								if (swakOTSList.length > 1) {
   									otswindow.document.write("<input type='button' id=\"swakotsprevious\" value='Previous' onclick='swakOTSPrevious(self)'/>");
   								}
   								else {
   									otswindow.document.write("<input type='button' id=\"swakotsprevious\" value='Previous' disabled onclick='swakOTSPrevious(self)'/>");
   								}
   								
   								otswindow.document.write("<input type='button' id=\"swakotsnext\" value='Next' disabled onclick='swakOTSNext(self)'/>");
   								otswindow.document.write("<span class=\"swakOTSNum\">Number of Results: " + swakOTSList.length + "</span>");
   								otswindow.document.write("</CENTER>");
   								otswindow.document.write("</DIV>");
   								otswindow.document.write("</BODY></HTML>");
   								otswindow.document.close();
   								
								}
								
								function swakOTSPrevious1(otswindow) {
									//alert('swakOTSPrevious ' + otswindow);
									if (otswindow == null) return;
									var otslist = otswindow.opener.swakOTSList;
		//							alert('swakOTSPrevious otswindow.opener.content.document ' + otswindow.opener.swakOTSList);
									if (otslist == null) return;
		//							alert('otslist len ' + otslist.length);
									
									//var odoct = otswindow.document.getElementById('liveObjectContainer');
									//alert('odoct ' + odoct.innerHTML);
									
									if (otswindow.opener.swakOTSListIndex == 0) {
										return;
									}
									var pindex = otswindow.opener.swakOTSListIndex - 1;
									if (pindex < 0) {
										return;
									}
									alert(otswindow.opener.swakOTSListIndex + ',swakOTSListIndex pindex ' +pindex);
									var oro = otslist[pindex];
									if (oro == null) return;
									var odoc = otswindow.document.getElementById('liveObjectContainer');
									odoc.innerHTML = oro.innerHTML;
									otswindow.opener.swakOTSListIndex = pindex;
								}
								
								function swakOTSNext1(otswindow) {
									if (otswindow == null) return;
									var otslist = otswindow.opener.swakOTSList;
									
									if (otslist == null) return;
									alert('otslist len ' + otslist.length);
									var nindex = otswindow.opener.swakOTSListIndex + 1;
									if (nindex > otslist.length -1) {
										return;
									}
									alert(otswindow.opener.swakOTSListIndex + ',swakOTSListIndex nindex ' +nindex);
									var oro = otslist[nindex];
									if (oro == null) return;
									var odoc = otswindow.document.getElementById('liveObjectContainer');
									odoc.innerHTML = oro.innerHTML;
									otswindow.opener.swakOTSListIndex = nindex;
								}
								
								function SwakShowLastSold() {
							//		alert('previous ots results '+ swakOTSInnerHtml);

									var soldwindow=window.open('','SwakSmack Sold Result','height=400,width=400,resizable=yes,scrollbars=yes');
									//otswindow.document.location.protocol="http:";
									//otswindow.document.location.host="www.jellyfish.com";
									soldwindow.title = "SwakSmack Sold Result";
   								soldwindow.document.write("<HTML>");
   								soldwindow.document.write("<HEAD>");
   								soldwindow.document.write("<link href=\"http://www.jellyfish.com/smack/stylesheets/smackV2.css?1192206863\" media=\"screen\" rel=\"Stylesheet\" type=\"text/css\">");
   								soldwindow.document.write("<link href=\"chrome://swaksmack/skin/swaksmack.css\" media=\"screen\" rel=\"Stylesheet\" type=\"text/css\">");
   								soldwindow.document.write("<script src=\"chrome://swaksmack/content/overlay.js\" type=\"text/javascript\"></script>");
   								soldwindow.document.write("</HEAD>");
   								soldwindow.document.write("<BODY>");
   								soldwindow.document.write("<DIV id=\"leftPanel\">");
   								soldwindow.document.write("<DIV id=\"liveObjectContainer\" class=\"swaksoldresultloc\">");
   								soldwindow.document.write(swakSoldInnerHtml);
   								soldwindow.document.write("</DIV>");
   								if (swakSmackPotSoldInnerHtml != null) {
   									soldwindow.document.write(swakSmackPotSoldInnerHtml);
   								}
   								soldwindow.document.write("</DIV>");
   								soldwindow.document.write("<DIV id=\"swakotsresultsclose\">");
   								soldwindow.document.write("<CENTER>");
   								soldwindow.document.write("<input type='button' value='Close' onclick='self.close()'/>");
   								soldwindow.document.write("<input type='button' value='Coins' onclick='swakSoldInfoCoins(self);'/>");
   								soldwindow.document.write("</CENTER>");
   								soldwindow.document.write("</DIV>");
   								soldwindow.document.write("</BODY></HTML>");
   								soldwindow.document.close();
   								
								}
								
								function swakSoldInfoCoins(soldWin){
								//	alert('swakSoldInfoCoins entry');
									if (soldWin == null) return;
									var spc = soldWin.document.getElementById('swakSmackPotResultsContainer');
									if (spc == null) return;
									var dv = spc.style.display;
									//alert('spc style ' + dv);
									/*
									if (dv == 'none' || dv == 'undefined' || dv == null) {
										spc.style.display='block';
									}
									else {
										spc.style.display='none';
									}
									*/
									if (dv == 'block') {
										spc.style.display='none';
									}
									else {
										spc.style.display='block';
									}
									/*
									if  (dv != '') {
										spc.style.display='';
									}
									else {
										spc.style.display='none';
									}
									*/
								}
								

								function chatClearKeywords(){
									//clear the dynamic keywords ad usernames
									//keywords specified in options are kept
									SS_dynamicKeywords = [];
									SS_dynamicUsernames = [];
									clearHighlightArrays();

								}

								function chatListKeywords(){
									//list keywords
									var words = SS_getPreference(SMACK_KEYWORDHL1);
									words += ', ';
									words += SS_getPreference(SMACK_KEYWORDHL2);
									words += ', ';
									words += SS_getPreference(SMACK_KEYWORDHL3);
	
									//alert('keyword ' + words);
									//alert('chatListKeywords SS_dynamicUsernames ' + SS_dynamicUsernames);
									var usernames = SS_getPreference(SMACK_USERNAMEHL1);	
									usernames += ', ';
									usernames += SS_getPreference(SMACK_USERNAMEHL2);
									usernames += ', ';
									usernames += SS_getPreference(SMACK_USERNAMEHL3);		
									
									//var usernames = SS_combinedUsernames.join(', ');
									var list = 'SwakSmack Keywords\n';
									if (words != '' && usernames != '') {
										list = list + '\nMain Keywords: \n';
										if (usernames != null) list = list + 'Usernames: ' + usernames +'\n';
										if (words != null) list = list + 'Keywords: ' + words +'\n';
									}
									if (SS_dynamicUsernames != null && SS_dynamicUsernames.length>0) {
										list = list + '\nDynamic Usernames: \n' +  SS_dynamicUsernames.toString();
									}
									if (SS_dynamicKeywords !=null && SS_dynamicKeywords.length>0) {
										list = list + '\nDynamic Keywords: \n' +  SS_dynamicKeywords.toString();
									}

									alert(list);
								}

								function toggleChat() {
									//alert('togglechat');
									if( isSmackShopArea(content.document) == false) {
										return;
									}
									var paused = swaksmack.SS_JF.toggleChat();
									//alert('paused ' + paused);
									//	var menuitem = document.getElementById("contextmenu-togglechat");
									var chatHeader = swaksmack.SmackShopDoc.getElementById('chatHeader');
									if (SS_ChatHeaderText == null || SS_ChatHeaderText == '') {
										SS_ChatHeaderText = chatHeader.innerHTML;
									}
									SS_chatHeaderChange = true;
									updateChatHeader();
									
									if (paused) {
										var pauseImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPause');
										pauseImg.style.display='none';
										var playImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPlay');
										playImg.style.display='';
									}
									else {	
										var pauseImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPause');
										pauseImg.style.display='';
										var playImg = swaksmack.SmackShopDoc.getElementById('swaksmackChatPlay');
										playImg.style.display='none';
									}
									
									//flag it again so thatthe status updates on the next post
									//this will return the header to normal
									SS_chatHeaderChange = true;
									return paused;
								}

								function updateChatHeader(resume) {
									if (swaksmack.SmackShopDoc == null || swaksmack.SS_JF == null) return;
									var chatHeader = swaksmack.SmackShopDoc.getElementById('chatHeader');
									if (chatHeader == null) return;
									if (SS_ChatHeaderText == null || SS_ChatHeaderText == '') {
										SS_ChatHeaderText = chatHeader.innerHTML;
									}
									if (resume == null) resume = false;
									var menuitem = document.getElementById("contextmenu-togglechat");
									var paused = swaksmack.SS_JF.isChatPaused();
									if (paused) {
										chatHeader.style.color = '#FF7800';
										menuitem.setAttribute("label",SS_getStringTableText("chat_resume"));
										var chatMsg = SS_getStringTableText("chat_paused1");
										chatHeader.innerHTML = SS_ChatHeaderText + "<b> : " + chatMsg+ "</b>";
									}
									else if (resume == false) {
										chatHeader.style.color = '#FF7800';
										menuitem.setAttribute("label",SS_getStringTableText("chat_pause"));
										var chatMsg = SS_getStringTableText("chat_resume1");
										var rn = SS_getRandomNumber(5);

										chatMsg = (rn <= 5)?SS_getStringTableText("chat_resume"+rn) : "chat_resume1";

										chatHeader.innerHTML = SS_ChatHeaderText + "<b> : " + chatMsg+ "</b>";

									}
									else {
										chatHeader.innerHTML = SS_ChatHeaderText;
									}


									if (swaksmack.smackCommentsHidden == true) {
										chatHeader.style.color = '#FF7800';
										var chatHidden = SS_getStringTableText('chat_header_display_hl_only');
										chatHeader.innerHTML = chatHeader.innerHTML + ' -- ' + chatHidden;
									}
									SS_chatHeaderChange = false;
								}

								function chatReply(event, pn) {

									//selection
									var replyText = '';

									if (gContextMenu.searchSelected)
									replyText = gContextMenu.searchSelected();
									else
										replyText = getBrowserSelection();
										if (replyText.length>0) {
											replyText = "\""+replyText+"\"";
										}


										//selection


										var ci = getCommentInfo(pn);
										//alert(pn.className + ' (org) --commentInfo element ' + ci.className);
										var chatNick = getElementChatNick(ci);
										//var chatNick = getElementsByClassName('chatNick',ci);


										var chatPrefix ='';
										if (chatNick != null && chatNick[0] != null) {
											var cpost = content.document.getElementById('comment_comment');
											cpost.value = buildReply(chatNick[0].textContent,replyText);
											cpost.focus();
											swakClearCurrentSelection();
										}
									}
									
									function isUsernameInDynamicHL(username) {
										if (username == null || username == '') return false;
										var index = SS_dynamicUsernames.indexOf(username);
										if (index != -1) {
											return true;
										}
										return false;
									}
									
									function addUserNameToDynamicHL(username) {
										if (username == null) return false;
										var index = SS_dynamicUsernames.indexOf(username);
										if (index == -1) {
											SS_dynamicUsernames.push(username);
											clearHighlightArrays();
											return true;
										}
										return false;
									}
									
									function removeUserNameFromDynamicHL(username) {
										if (username == null) return;
										var removeNameIndex = SS_dynamicUsernames.indexOf(username);
										//alert('remove name index ' + removeNameIndex);
										if (removeNameIndex != -1) {
											if (removeNameIndex == 0 ) {
												SS_dynamicUsernames.shift();
												clearHighlightArrays();
											}
											else if(removeNameIndex ==SS_dynamicUsernames.length-1){
												SS_dynamicUsernames.pop();
												clearHighlightArrays();
											}
											else {
												SS_dynamicUsernames = SS_dynamicUsernames.splice(1,removeNameIndex);
												clearHighlightArrays();
											}
										}
									}

									function getCommentInfo(commentNode) {
										try {
											if (commentNode == null) return null;
											if (commentNode.className == 'commentInfo') return commentNode;
											else if (commentNode.className == 'commentText') return commentNode.parentNode;
												else if (commentNode.className == 'chatNick') return commentNode.parentNode;
													else if (commentNode.className == 'chatGuru') return commentNode.parentNode;
														else if (commentNode.className == 'chatTime') return commentNode.parentNode;
															else if (commentNode.className == 'swaksmackHighlightUser') return commentNode.parentNode;
																else if (commentNode.className == 'swaksmackUnhighlightUser') return commentNode.parentNode;
																	else if (commentNode.className == 'swaksmackReply') return commentNode.parentNode;
																		else if (commentNode.className == 'chatAvatar') {
																			//not as straightforward, but navigation is simple
																			//find chatPost and then commentInfo
																			//alert('chatAvatar class found, parent parent parent className ' + commentNode.parentNode.parentNode.parentNode.className);
																			var cChatPost = commentNode.parentNode.parentNode.parentNode;
																			//minor recursion to find info from chatPost
																			return getCommentInfo(cChatPost);
																		}
																		else if (commentNode.className == 'chatPost') {
																			//the 3rd child of the chat post is the commentinfo
																			var ci = commentNode.childNodes[2];
																			if (ci != null && ci.className == 'commentInfo') {
																				return ci;
																			}
																			return null;
																		}
																		else {
																			//alert('unhandled commentNode.className ' + commentNode.className);
																			return null;
																		}
																		return null;
																	}
																	catch (Exception){
																		swakAddException(x);
																		return null;
																	}
																}
																
		function swakActionIgnore() {
			var ctx = swaksmack.postPopupNode;
			var ci = getCommentInfo(ctx);
			var chatNick = getElementChatNick(ci,swaksmack.SmackShopDoc);
			//var chatNick = getElementsByClassName('chatNick',ci);
			var username = chatNick[0].textContent;
			var msg = "Ignore that no good, lily-livered, blight on society miscreant " + username + "?";
			var ans = confirm(msg);
			if (ans) {
				var result = swakAppendWordToCharPref(username,SMACK_IGNORELIST1);
				if (result) {
					clearHighlightArrays();
				}
			}
		}
		
		function swakActionReplaceAvatar() {
			var ctx = swaksmack.postPopupNode;
			var ci = getCommentInfo(ctx);
			var chatNick = getElementChatNick(ci,swaksmack.SmackShopDoc);
			//var chatNick = getElementsByClassName('chatNick',ci);
			var username = chatNick[0].textContent;
			var msg = "Replace avatar for " + username + "?";
			var ans = confirm(msg);
			if (ans) {
				var result = swakAppendWordToCharPref(username,SMACK_IGNOREAVATARLIST);
				if(result) {
					JF_ignoreAvatarlistRegExp = null;
				}
			}
		}
		
		function swakActionInitHighlight(event) {
			var username = swakActionGetNickName();
			var exists1 = swakDoesCharPrefContain(username, SMACK_USERNAMEHL1);
			if (exists1 == true) {
				var mi = document.getElementById('swaksmack-action-hl1');
				mi.setAttribute('label','Remove from Highlight List 1');
			}
			else {
				var mi = document.getElementById('swaksmack-action-hl1');
				mi.setAttribute('label','Add to Highlight List 1');
			}
			
			var exists2 = swakDoesCharPrefContain(username, SMACK_USERNAMEHL2);
			if (exists2 == true) {
				var mi = document.getElementById('swaksmack-action-hl2');
				mi.setAttribute('label','Remove from Highlight List 2');
			}
			else {
				var mi = document.getElementById('swaksmack-action-hl2');
				mi.setAttribute('label','Add to Highlight List 2');
			}
			
			var exists3 = swakDoesCharPrefContain(username, SMACK_USERNAMEHL3);
			if (exists3 == true) {
				var mi = document.getElementById('swaksmack-action-hl3');
				mi.setAttribute('label','Remove from Highlight List 3');
			}
			else {
				var mi = document.getElementById('swaksmack-action-hl3');
				mi.setAttribute('label','Add to Highlight List 3');
			}
			
			var fup = document.getElementById('swaksmack-action-find');
			var selectedName = null;
			try {
				if (gContextMenu && gContextMenu.searchSelected) 
					selectedName = gContextMenu.searchSelected();
				else
					selectedName = getBrowserSelection();
			}
			catch (x) {selectedName = null;}
			
			
			if (username == null) {
				fup.setAttribute('label','Find User\'s Posts');
			}
			else {
				var str = 'Find ';
				if (selectedName != null && selectedName != '') {
					str+=selectedName + '\'s Posts'
				}
				else {
					str+=username + '\'s Posts'
				}
				fup.setAttribute('label',str);
			}
			

		}
		
		function swakActionHighlight1() {
			var username = swakActionGetNickName();
			var exists = swakDoesCharPrefContain(username, SMACK_USERNAMEHL1);
			if (exists == false) {
				swakActionAddHighlightedUser(username,SMACK_USERNAMEHL1);
			}
			else {
				swakRemoveWordFromCharPref(username,SMACK_USERNAMEHL1);
				clearHighlightArrays();
			}
		}
		
	  function swakActionHighlight2() {
	  	var username = swakActionGetNickName();
			var exists = swakDoesCharPrefContain(username, SMACK_USERNAMEHL2);
			if (exists == false) {
				swakActionAddHighlightedUser(username,SMACK_USERNAMEHL2);
			}
			else {
				swakRemoveWordFromCharPref(username,SMACK_USERNAMEHL2);
				clearHighlightArrays();
			}
	  	
		}	
		
		function swakActionHighlight3() {
	  	var username = swakActionGetNickName();
			var exists = swakDoesCharPrefContain(username, SMACK_USERNAMEHL3);
			if (exists == false) {
				swakActionAddHighlightedUser(username,SMACK_USERNAMEHL3);
			}
			else {
				swakRemoveWordFromCharPref(username,SMACK_USERNAMEHL3);
				clearHighlightArrays();
			}
						
		}
		
		function swakActionFindUsersPosts() {
			var selectedName = null;
			try {
				if (gContextMenu && gContextMenu.searchSelected) 
					selectedName = gContextMenu.searchSelected();
				else
					selectedName = getBrowserSelection();
			}
			catch (x) {selectedName = null;}
			if (selectedName == null || selectedName == '') {
				selectedName = swakActionGetNickName();
			}
			if (selectedName == null || selectedName == '') return;
			findUsername(selectedName);
			//now clear any selected name/word
			try {
				swaksmack.postPopupNode.focus();
				swakClearCurrentSelection();
			}
			catch(x){
				swakAddException(x);
			}
		}
		
		function swakActionGetNickName() {
			try {
				var ctx = swaksmack.postPopupNode;
				var ci = getCommentInfo(ctx);
				var chatNick = getElementChatNick(ci,swaksmack.SmackShopDoc);
				//var chatNick = getElementsByClassName('chatNick',ci);
				var username = chatNick[0].textContent;
				return username;
			}
			catch (x) {
				swakAddException(x);
			}
			return null;
		}
		
		function swakActionAddHighlightedUser(username, hlpref) {
			var result = swakAppendWordToCharPref(username,hlpref);
			if (result) {
				clearHighlightArrays();
				highlightExistingComments(swaksmack.SmackShopDoc);
			}					
		}		
		
		function swakActionPhotoAlbum() {
			var ctx = swaksmack.postPopupNode;
			var ci = getCommentInfo(ctx);
			var chatNick = getElementChatNick(ci,swaksmack.SmackShopDoc);
			//var chatNick = getElementsByClassName('chatNick',ci);
			var ref = chatNick[0].getAttribute('href');
			var paurl = 'http://www.jellyfish.com' + ref + '/photoAlbum';
			Swak_openUrl(paurl,true);
		}
		
		function swakActionShoppingBuddies() {
			var ctx = swaksmack.postPopupNode;
			var ci = getCommentInfo(ctx);
			var chatNick = getElementChatNick(ci,swaksmack.SmackShopDoc);
			//var chatNick = getElementsByClassName('chatNick',ci);
			var ref = chatNick[0].getAttribute('href');
			var paurl = 'http://www.jellyfish.com' + ref + '/shoppingBuddies';
			Swak_openUrl(paurl,true);
		}	

		function swakActionShoppingList() {
			var ctx = swaksmack.postPopupNode;
			var ci = getCommentInfo(ctx);
			var chatNick = getElementChatNick(ci,swaksmack.SmackShopDoc);
			//var chatNick = getElementsByClassName('chatNick',ci);
			var ref = chatNick[0].getAttribute('href');
			var paurl = 'http://www.jellyfish.com' + ref + '/lists';
			Swak_openUrl(paurl,true);
		}			
		
		function swakSBPopupInit(event) {
			var sbpudebug = document.getElementById('ss-sb-pu-showdebug');
			if (sbpudebug != null) {
				var debugenabled = SS_getPreference(SMACK_DEBUGENABLED);
				if (debugenabled == true) {
					sbpudebug.setAttribute('hidden','false');
				}
				else {
					sbpudebug.setAttribute('hidden','true');
				}
			}
			var sbpuots = document.getElementById('ss-sb-pu-showots');
			if (sbpuots != null) {
				if (swakOTSInnerHtml == null) {
					sbpuots.setAttribute('hidden','true');
				}
				else {
					sbpuots.setAttribute('hidden','false');
				}
			}
			
			var sbpusold = document.getElementById('ss-sb-pu-showsold');
			if (sbpusold != null) {
				if (swakSoldInnerHtml == null) {
					sbpusold.setAttribute('hidden','true');
				}
				else {
					sbpusold.setAttribute('hidden','false');
				}
			}
			
		}
		
		function swakCMPopupInit(event) {
			var sbpudebug = document.getElementById('contextmenu-showdebug');
			if (sbpudebug != null) {
				var debugenabled = SS_getPreference(SMACK_DEBUGENABLED);
				if (debugenabled == true) {
					sbpudebug.setAttribute('hidden','false');
				}
				else {
					sbpudebug.setAttribute('hidden','true');
				}
			}
			var sbpuots = document.getElementById('contextmenu-showots');
			if (sbpuots != null) {
				if (swakOTSInnerHtml == null) {
					sbpuots.setAttribute('hidden','true');
				}
				else {
					sbpuots.setAttribute('hidden','false');
				}
			}
			
			var sbpusold = document.getElementById('contextmenu-showsold');
			if (sbpusold != null) {
				if (swakSoldInnerHtml == null) {
					sbpusold.setAttribute('hidden','true');
				}
				else {
					sbpusold.setAttribute('hidden','false');
				}
			}
			
		}																

		function setChatSpeed() {
			try {
				var speed = SS_getPreference(SMACK_CHATSPEED);
				swaksmack.SS_JF.setChatSpeed(speed);
			}
			catch (Exception) {}
		}
		
		function playdelayedsound() {
			//if (param == null) return;
			//alert('delayed sound');
			var soundFile = SS_getPreference(SMACK_AUDIOSOUND_PM);
			swaksmack.audioManager.playAudioAlert(soundFile);
		}

		function updatePMLR() {
			var pmAlert = swaksmack.SmackShopDoc.getElementById('alertEnvelope');
			var contextAlert = content.document.getElementById('alertEnvelope');
			if ((pmAlert != null && pmAlert.className == 'new') || (contextAlert != null && contextAlert.className == 'new')) {		
				if (swakalerts.pmSoundPlayed == false) {
					
						swaksmack.SS_SBM.flashPMButton(-1);
						//there is currently a problem with JF and the PM indicator where it goes on and off
						//"randomly".  This happens even without the extension
		//				alert(contextAlert.className + ' (ca) updatePMLR pmAlert.className3576 ' +pmAlert.className);
						swakalerts.pmSoundPlayed = true;
			//			var soundFile = SS_getPreference(SMACK_AUDIOSOUND_PM);
				//	setTimeout("playdelayedsound()", 2000);
		//				setTimeout("playdelayedsound("+soundFile+")", 2000);
		//				swaksmack.audioManager.playAudioAlert(soundFile);
				}
				
			}
			else if ((pmAlert != null && pmAlert.className == 'noNew')) {// || (contextAlert != null && contextAlert.className == 'noNew')) {
				if (swakalerts.pmSoundPlayed == true) {
					swaksmack.SS_SBM.setPMStatusOff();
					swakalerts.pmSoundPlayed = false;
				}
			}
			
			var chatAlert= swaksmack.SmackShopDoc.getElementById('alertChat');
			contextAlert = content.document.getElementById('alertChat');
			if ((chatAlert != null && chatAlert.className == 'new') || (contextAlert != null && contextAlert.className == 'new')) {	
				if (swakalerts.lrSoundPlayed == false) {
					swaksmack.SS_SBM.setLRStatusOn();
					swakalerts.lrSoundPlayed = true;
				}
			}
			else if ((chatAlert != null && chatAlert.className == 'noNew')) {// || (contextAlert != null && contextAlert.className == 'noNew')) {
				if (swakalerts.lrSoundPlayed == true) {
					swaksmack.SS_SBM.setLRStatusOff();
					swakalerts.lrSoundPlayed = false;
				}
			}
		}
		
		
		function onPMUpdate(prevPM, pmValue, prevChat, chatValue) {
			//alert(pmValue+ ' onPMUpdate ' + chatValue);
			//if there is change, update the main smack page and any current page indicator
			if (pmValue != prevPM) {
				var pmAlert = swaksmack.SmackShopDoc.getElementById('alertEnvelope');
				var contextAlert = content.document.getElementById('alertEnvelope');
				if (pmValue == true) {
					pmAlert.className = '';
					if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = '';
					swaksmack.SS_SBM.flashPMButton(-1);
					if (swakalerts.pmSoundPlayed == false) {
						swakalerts.pmSoundPlayed = true;
						var soundFile = SS_getPreference(SMACK_AUDIOSOUND_PM);
						swaksmack.audioManager.playAudioAlert(soundFile);
					}
				}
				else {
					pmAlert.className = 'noNew';
					if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = 'noNew';
					swaksmack.SS_SBM.setPMStatusOff();
					swakalerts.pmSoundPlayed = false;
				}
			}
			if (chatValue != prevChat) {
				var chatAlert= swaksmack.SmackShopDoc.getElementById('alertChat');
				contextAlert = content.document.getElementById('alertChat');
				if (chatValue == true) {
					chatAlert.className = '';
					if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = '';
					swaksmack.SS_SBM.setLRStatusOn();
					if (swakalerts.lrSoundPlayed == false) {
						swakalerts.lrSoundPlayed = true;
						var soundFile = SS_getPreference(SMACK_AUDIOSOUND_LR);
						swaksmack.audioManager.playAudioAlert(soundFile);
				}
				}
				else {
					chatAlert.className = 'noNew';
					if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = 'noNew';
					swaksmack.SS_SBM.setLRStatusOff();
					swakalerts.lrSoundPlayed = false;
				}
			}
		}



		//guru guess calc
		function launchCalcWindow() {
			if (SS_GGCalcWindow == null || SS_GGCalcWindow.closed == true) {
	
				SS_GGCalcWindow=window.open('chrome://swaksmack/content/ggcalc.xul','SwakSmack Guru Calculator','height=400,width=500');
	
			}
			else {
				//we close and then create a new window because some of the elements
				//the popup depends on are replaced whem the liveconatinerobject has
				//its innerhtml updated
				SS_GGCalcWindow.close();
	
				SS_GGCalcWindow=window.open('chrome://swaksmack/content/ggcalc.xul','SwakSmack Guru Calculator','height=400,width=500');
	
	
			}
	
	
			//create popup object--revisit
			if ( SS_ggcalc == null) {
				SS_ggcalc = new GGCalc();
			}
			SS_ggcalc.popup=SS_GGCalcWindow;
		}
	
		function SS_onOptionsUpdate() {
			clearHighlightArrays();
		}
		
		
		function addProductImageFlyout() {
			//alert('addProductImageFlyout entry');
			if (swaksmack.SmackShopDoc == null) return;
			var existing = swaksmack.SmackShopDoc.getElementById('swakProductImage');
			if (existing != null) return;
			//alert('addProductImageFlyout new entry');
			var prodimg = swaksmack.SmackShopDoc.getElementById('productImage');
			var itemPhoto = swaksmack.SmackShopDoc.getElementById('itemPhoto'); //itemPhoto
			if (prodimg == null || itemPhoto == null) return;
			var largeImage = getLargeItemPhoto(prodimg);
			if (largeImage == null || largeImage == '') {
				largeImage = 'chrome://swaksmack/skin/images/productImage404-1.jpg';
			}
			
			var foidiv = swaksmack.SmackShopDoc.createElement("div");
			var img = swaksmack.SmackShopDoc.createElement("img");
			img.setAttribute('id','swakProductImage');
			var rn = SS_getRandomNumber(2);
			if (rn < 2) 
			{
				img.setAttribute('onerror','this.src=\'chrome://swaksmack/skin/images/productImage404-1.jpg\'');
			}
			else {
				img.setAttribute('onerror','this.src=\'chrome://swaksmack/skin/images/productImage404-2.jpg\'');
			}
			img.setAttribute('src',largeImage);
		  foidiv.setAttribute('id','swakProductImageContainer');

			foidiv.style.height='0px';
			foidiv.style.width='0px';		
										
			foidiv.appendChild(img);
			itemPhoto.appendChild(foidiv);
			prodimg.addEventListener('mouseover',  function(event) {
									foidiv.style.height='1px';
									foidiv.style.width='1px';
									foidiv.style.overflow='visible';									
										}, false);
										
			prodimg.addEventListener('mouseout',  function(event) {
									foidiv.style.height='0px';
									foidiv.style.width='0px';
									foidiv.style.overflow='hidden';
									
										}, false);	
																			

			swakInsertDealEndTime();

		}
		
		function getLargeItemPhoto(photoImage) {
			if (photoImage == null) return '';
			var s = photoImage.getAttribute('src');
			if (s == null || s =='') return '';
			//s = s.replace(/_m[.]jpg/g, ".jpg").replace(/_m[.]png/g, ".png");
			s = s.replace(/_m[.](jpg|png|gif)/g, ".$1");
			return s;
		}
		
		function swakSetException(x) {
			swakAddException(x);
			if (swakException == null) {
				swakException = x;
			}
		}
		
		var swakAddExceptionAck = false;
		function swakAddException(x) {
			try {
				if (swakExceptionList != null) {
					if (swakExceptionList.length >= 20) {
						swakExceptionList.shift();
					}
					var d = new Date();
					swakExceptionList.push(d + ':  ' + x);
					if (SS_getPreference(SMACK_DEBUGENABLED)) {
						var debuginfo = swakExceptionList.join(' :: '); 
						ssopts.setCharPref(SMACK_DEBUGINFO,debuginfo);
					}
				}
			}
			catch(sae){
				if (swakAddExceptionAck == false) {
					swakAddExceptionAck = true;
					alert('Please tell Mindstorm about this error: ' + sae);
				}
			}
		}		

		var swakalerts = {
			outwitAlertAck: false,
			outwitVoteAck: false,
			smakpotAlertAck: false,
			guruguessAlertAck: false,
			pmSoundPlayed: false,
			lrSoundPlayed: false,
		}

		var swaksmack = {
			jfdoc:null,
			SS_SBM:null,
			SS_JF:null,
			SmackShopDoc:null,
			LivingRoomDoc:null,
			alertManager:null,
			audioManager:null,
			smackchatIdArray:null,
			smackLRIdArray:null,
			smackShopContentWindow:null,
			smackCommentsHidden: false,
			lrCommentsHidden: false,
			ignoreListCurrent: false,
			lastPMCheckTime: null,
			PMChecker: null,
			coinsWonDuringShow: 0,
			coinsWonOnLastItem: 0,
			coinsWonDuringSession: 0,
			productListenerAdded: false,
			postPopupNode: null,
			smackFunController: null,
			lastOTSResult: null,
			setdoc: function(d) {
				swaksmack.jfdoc = d;
			},
			onLoad: function() {
				getBrowser();
				// initialization code
				this.initialized = true;
				this.strings = document.getElementById("swaksmack-strings");
				document.getElementById("contentAreaContextMenu")
				.addEventListener("popupshowing", function(e) { this.showContextMenu(e); }, false);
				//add onload listener for web pages
				var appcontent = document.getElementById("appcontent");   // browser
				if(appcontent) {
					appcontent.addEventListener("load", this.onPageLoad, true);
					appcontent.addEventListener("load", this.showContextMenu, true);
					//test
					appcontent.addEventListener("unload", this.onPageUnload, true);
				}

				SwakPrefWatcher.init();


			},
			onPageLoad: function(aEvent) {
				var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
				// do something with the loaded page.
				// doc.location is a Location object (see below for a link).
				// You can use it to make your code executed on certain pages only.


				if (checkHost(doc) == true) {
					//alert('onpageload');

					if (swaksmack.SS_JF == null) {
						swaksmack.SS_JF = new JellyFish();
					}

					swaksmack.smackLRIdArray = new Array();

					var shoppingArea = false;
					shoppingArea = isSmackShopArea(doc);
					//alert('JF smack aread found ' + shoppingArea);
					//store doc ref for smack shopping document
					if (shoppingArea == true) {
						//alert('smack area found');
						swaksmack.SmackShopDoc = doc;
						SS_window = window;
						swaksmack.smackShopContentWindow = gBrowser.contentWindow;
						swaksmack.smackchatIdArray = new Array();
						registerSmackChatListeners(swaksmack.SmackShopDoc);
						updateDisplayHighlightedUI(swaksmack.SmackShopDoc);
						updateChatThemeCSS(swaksmack.SmackShopDoc);
						addPlayPause(swaksmack.SmackShopDoc);
					}

					//enable for offline guruguess test
					if (false) {
						//temp for gg calc test
						swaksmack.SmackShopDoc = doc;
						registerSmackChatListeners(swaksmack.SmackShopDoc);
					}

					//check to see if in the private message area


					if (isPMArea(doc) == true) {
						applyPMCSS(doc);
						executePMLink(SMACK_PMDIV, doc);
						return;
					}
					else if (isLRArea(doc) == true) {
						swaksmack.LivingRoomDoc = doc;
						registerLivingRoomChatListeners(swaksmack.LivingRoomDoc);
						updateDisplayHighlightedUI(swaksmack.LivingRoomDoc);
					}
					commentSpellCheck(doc);
					chatLinkColor(doc);

					clearHighlightArrays();



					//register listener on the chat post for tinyurl
					registerChatPostListener(doc);
					if (swaksmack.alertManager == null)
					swaksmack.alertManager = new SSAlertManager();
					if (swaksmack.audioManager == null)
					swaksmack.audioManager = new AudioManager();

					swaksmack.SS_SBM.setKWStatusConnected();
					if (shoppingArea == true) {
						swaksmack.SS_SBM.monitorState(SS_getPreference(SMACK_SBSALEINTERVAL));
					}
					else {
						//alert('not shopping area');
					}


					if (SS_getPreference(SMACK_CHECKPMCHAT) == true) {
						if (swaksmack.PMChecker != null) {
							swaksmack.PMChecker.stopCheck();
						}
						swaksmack.PMChecker = new JellyFishPMChecker();
						swaksmack.PMChecker.setInterval(SS_getPreference(SMACK_CHECKPMINTERVAL));
						swaksmack.PMChecker.checkPM();
					}

					//menu stuff

					var menu = document.getElementById("contentAreaContextMenu");
					//alert(menu);
					menu.addEventListener("popupshowing", swakContextShowing, false);
					swakContextVisibilityOn();

					//http://developer.mozilla.org/en/docs/Code_snippets:Tabbed_browser#Closing_a_tab
					var container = gBrowser.tabContainer;
					container.addEventListener("TabClose", swaksmack.tabRemoved, false);
					container.addEventListener("TabSelect", swaksmack.tabSelected, false);

					if (SS_getPreference(SMACK_ENHANCEHIDEAVATARS)) {
						hideAllAvatarImages();
					}


					swaksmack.setdoc(doc);
					//late init stuff
					if (swaksmack.smackShopContentWindow == null || swaksmack.SmackShopDoc == null) {
						if (isSmackShopArea(doc) == true) {
							swaksmack.smackShopContentWindow = gBrowser.contentWindow;
							swaksmack.SmackShopDoc = doc;
						}
					}
					swaksmack.smackFunController = SwakFunMode;
					var funMode= SS_getPreference(SMACK_FUNIGNORE1);
					var customFun = SS_getPreference(SMACK_ENABLE_FUNLIST);
					if (funMode && customFun) {
						swaksmack.smackFunController.initFunMode();
					}

				}
			},
			onPageUnload: function(aEvent) {
				try {
					var doc = aEvent.originalTarget;
					var	host = doc.location.host;
					if (swaksmack.smackShopContentWindow == gBrowser.contentWindow) {
						if (checkHost(doc) == true && isSmackShopArea(doc)) {
							swaksmack.updateConnectedStatus(aEvent);
							swaksmack.SS_SBM.stopMonitorState();
						}
						updateDisplayHighlightedUI(swaksmack.SmackShopDoc);
						swaksmack.dispose();
					}
				}
				catch(x){}


			},
			showContextMenu: function(event) {
				// show or hide the menuitem based on what the context menu is on
				// see http://kb.mozillazine.org/Adding_items_to_menus
				//document.getElementById("context-jellyfish").hidden = gContextMenu.onImage;  //org
				//document.getElementById("context-swacksmack").hidden = !checkHost();
			},
			onMenuItemCommand: function(e) {

				//no longer needed for chat/url processing --remove menu item???
				//execute(SMACK_OUTWITCHATDIV);
				//externalLinks();


			},
			tabRemoved: function(event) {
				try {
					var browser = event.target.linkedBrowser;
					//alert('jf tab removed ' + event.originalTarget);
					var doc = content.document;
					if (swaksmack.smackShopContentWindow == browser.contentWindow) {
						swaksmack.updateConnectedStatus(event);
						swaksmack.SS_SBM.stopMonitorState();
						updateDisplayHighlightedUI(swaksmack.SmackShopDoc);
						swaksmack.dispose();
					}
				}
				catch(x){}


			},
			dispose: function() {
				if (swaksmack.PMChecker != null) {
					swaksmack.PMChecker.stopCheck();
					swaksmack.PMChecker = null;
				}
				swaksmack.smackShopContentWindow = null;
				swaksmack.smackCommentsHidden = false;
				swaksmack.smackchatIdArray = [];
				JF_ignoreUserlistRegExp = null;
				JF_ignoreWordlistRegExp = null;
				JF_ignoreAttendancelistRegExp = null;
//				JF_keywordlistRegExp = null;
//				JF_usernamelistRegExp = null;
				JF_usernameArray = [];
				JF_keywordArray = [];
			},
			tabSelected: function(event) {
				try {

					updateDisplayHighlightedUI(content.document);
					//alert('tabselected updated display UI');
				}
				catch (x){}
			},
			updateConnectedStatus: function(event) {
				//alert(' swak updateConnectedStatus ');
				if (swaksmack.SS_SBM == null)
				swaksmack.SS_SBM = new StatusBarManager();
				swaksmack.SS_SBM.setKWStatusDisabled();
				swaksmack.SS_SBM.setSaleStatusDisconnected();


			},
			getUserGuess: function() {
				if (swaksmack.SmackShopDoc == null) return null;
				//alert('ss testdoc' + swaksmack.testdoc);
				return  swaksmack.SmackShopDoc.getElementsByName('user_guess');
			}

		};

			var SwakPrefWatcher = {
				prefs: null,
				hlUpdated: false,
				themeUpdated: false,
				funModeUpdated: false,
				init: function() {
					this.prefs = Components.classes["@mozilla.org/preferences-service;1"]
					.getService(Components.interfaces.nsIPrefService)
					.getBranch("extensions.swaksmack.");
					this.prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
					this.prefs.addObserver("", this, false);
					this.initStatusBar();
					this.initAudio();
					this.initAlerts();


				},
				initStatusBar: function() {
					if (swaksmack.SS_SBM == null) {
						//SS_SBM = new StatusBarManager();
						swaksmack.SS_SBM = new StatusBarManager();
						var sb1 = document.getElementById('swak-sb-kw-status');
						swaksmack.SS_SBM.setKWStatusBarPanel(sb1);

						var sbpm = document.getElementById('swak-sb-pm-status');
						swaksmack.SS_SBM.setPMStatusBarPanel(sbpm);

						var sblr = document.getElementById('swak-sb-lr-status');
						swaksmack.SS_SBM.setLRStatusBarPanel(sblr);

						var sbsale = document.getElementById('swak-sb-sale-status');

						swaksmack.SS_SBM.setSaleStatusBarPanel(sbsale);
					}
					var hid = this.prefs.getBoolPref("appearance.displaystatusbarpm_boolpref1");
					swaksmack.SS_SBM.hidePM(!hid);

					hid = this.prefs.getBoolPref("appearance.displaystatusbarlr_boolpref1");
					swaksmack.SS_SBM.hideLR(!hid);

					hid = this.prefs.getBoolPref("appearance.displaystatusbarkw_boolpref1");
					swaksmack.SS_SBM.hideKW(!hid);

					hid = this.prefs.getBoolPref("appearance.displaystatusbarsale_boolpref1");
					swaksmack.SS_SBM.hideSale(!hid)
				},
				initAudio: function() {
					var audio = document.getElementById('ss-sb-pu-audio');
					var enabled = this.prefs.getBoolPref("audio.global_enable_boolpref");
					audio.setAttribute('checked',enabled);
					audio = document.getElementById('contextmenu-audio');
					audio.setAttribute('checked',enabled);

				},
				initAlerts: function() {
					var alerts = document.getElementById('ss-sb-pu-alerts');
					var enabled = this.prefs.getBoolPref("alerts.global_enable_boolpref");
					alerts.setAttribute('checked',enabled);
					alerts = document.getElementById('contextmenu-alerts');
					alerts.setAttribute('checked',enabled);

				},
				shutdown: function() {
					this.prefs.removeObserver("", this);
				},
				onUpdate: function() {
					//alert('prefs updated');
					if (this.themeUpdated == true) {
						updateChatThemeCSS(swaksmack.SmackShopDoc);
					}
					if (this.hlUpdated == true) {
						clearHighlightArrays();
						highlightExistingComments(swaksmack.SmackShopDoc);
					}
					if (this.funModeUpdated == true) {
						var enabled = this.prefs.getBoolPref("ignore.funignore_boolpref1");
						if (enabled) {
							swaksmack.smackFunController.initFunMode();
						}
						
					}
					this.hlUpdated = false;
					this.themeUpdated = false;
					this.funModeUpdated = false;
				},
				observe: function(subject, topic, data) {
					if (topic != "nsPref:changed") {
						return;
					}

					switch(data) {
						case "appearance.displaystatusbarpm_boolpref1":
							if (swaksmack.SS_SBM == null) return;
							var hid = this.prefs.getBoolPref("appearance.displaystatusbarpm_boolpref1");
							swaksmack.SS_SBM.hidePM(!hid);
							break;
						case "appearance.displaystatusbarlr_boolpref1":
							if (swaksmack.SS_SBM == null) return;
							var hid = this.prefs.getBoolPref("appearance.displaystatusbarlr_boolpref1");
							swaksmack.SS_SBM.hideLR(!hid);
							break;
						case "appearance.displaystatusbarkw_boolpref1":
							if (swaksmack.SS_SBM == null) return;
							var hid = this.prefs.getBoolPref("appearance.displaystatusbarkw_boolpref1");
							swaksmack.SS_SBM.hideKW(!hid);
							break;
						case "appearance.ignoreavatarlist_stringpref":
						case "appearance.ignoreallavatars_boolpref1":
							JF_ignoreAvatarlistRegExp = null;
							break;	
						case "appearance.displaystatusbarsale_boolpref1":
							if (swaksmack.SS_SBM == null) return;
							var hid = this.prefs.getBoolPref("appearance.displaystatusbarsale_boolpref1");
							swaksmack.SS_SBM.hideSale(!hid);
							break;
						case "audio.global_enable_boolpref":
							var enabled = this.prefs.getBoolPref("audio.global_enable_boolpref");
							var audio = document.getElementById('ss-sb-pu-audio');
							audio.setAttribute('checked',enabled);
							audio = document.getElementById('contextmenu-audio');
							audio.setAttribute('checked',enabled);
							break;
						case "alerts.global_enable_boolpref":
							var enabled = this.prefs.getBoolPref("alerts.global_enable_boolpref");
							var alerts = document.getElementById('ss-sb-pu-alerts');
							alerts.setAttribute('checked',enabled);
							alerts = document.getElementById('contextmenu-alerts');
							alerts.setAttribute('checked',enabled);
							break;
						case "hl.usernamehl1_stringpref":
						case "hl.usernamehl2_stringpref":
						case "hl.usernamehl3_stringpref":
						case "hl.usernameignore1_stringpref":
						case "hl.usernameignore2_stringpref":
						case "hl.usernameignore3_stringpref":
							this.hlUpdated = true;
							break;
						case "hl.keywordshl1_stringpref":
						case "hl.keywordshl2_stringpref":
						case "hl.keywordshl3_stringpref":
						case "hl.keywordignore1_stringpref":
						case "hl.keywordignore2_stringpref":
						case "hl.keywordignore3_stringpref":
						case "hl.ignorecasehl_boolpref1":
						case "hl.chatwildcard1_boolpref1":
						case "hl.chatwildcard2_boolpref1":
						case "hl.chatwildcard3_boolpref1":
						case "hl.dynamicusername_stringpref":
						case "hl.dynamickeyword_stringpref":
						case "hl.chatinfohl1_boolpref1":
						case "hl.chatinfohl2_boolpref1":
						case "hl.chatinfohl3_boolpref1":
						case "hl.enablehl1_boolpref1":
						case "hl.enablehl2_boolpref1":
						case "hl.enablehl3_boolpref1":
							this.hlUpdated = true;
							break;
						case "ignore.ignorelist1_stringpref":
						case "ignore.ignorelist2_stringpref":
						case "ignore.ignorelistattend1_stringpref":
							swaksmack.ignoreListCurrent = true;
							JF_ignoreUserlistRegExp = null;
							JF_ignoreWordlistRegExp = null;
							JF_ignoreAttendancelistRegExp = null;
							break;
						case "theme.enabletheme_boolpref1":
						case "theme.textcolor1_stringpref":
						case "theme.bkcolor1_stringpref":	
						case "theme.chatActions_stringpref":
							this.themeUpdated = true;
							break;
						case "options.updated_boolpref":
							var updateComplete = this.prefs.getBoolPref("options.updated_boolpref");
							if (updateComplete == true) {
								this.onUpdate();
							}
							this.hlUpdated = false;
							this.themeUpdated = false;
							break;
						case "ignore.funignore_boolpref1":
						case "ignore.userfunlistfile_stringpref":
					  case "ignore.enableuserfunlist_boolpref1":	
							this.funModeUpdated = true;
							this.onUpdate();
							break;								
					}
				}

			}
			window.addEventListener("load", function(e) { swaksmack.onLoad(e); }, false);

